ToBytes() 공개 메소드

public ToBytes ( ) : byte[]
리턴 byte[]
예제 #1
0
    public byte[] ToBytes()
    {
        ByteBuffer byteBuffer = new ByteBuffer();

        byteBuffer.WriteByte((Byte)PrefabName.Length);
        byteBuffer.WriteString(PrefabName);

        byteBuffer.WriteInt((int)(X * 100f));
        byteBuffer.WriteInt((int)(Y * 100f));
        byteBuffer.WriteInt((int)(Z * 100f));

        byteBuffer.WriteShort((short)(RotationX * 100f));
        byteBuffer.WriteShort((short)(RotationX * 100f));
        byteBuffer.WriteShort((short)(RotationX * 100f));


        byteBuffer.WriteShort((short)(ScaleX * 100f));
        byteBuffer.WriteShort((short)(ScaleY * 100f));
        byteBuffer.WriteShort((short)(ScaleZ * 100f));

        byteBuffer.WriteByte((Byte)(type));
        if (type != GameObjectTypes.Block)
        {
            return(byteBuffer.ToBytes());
        }
        byteBuffer.WriteByte((Byte)(ColliderType));
        byteBuffer.WriteShort((Byte)(Radius * 100f));
        if (ColliderType == ColliderTypes.CapsuleCollider)
        {
            byteBuffer.WriteShort((Byte)(Height * 100f));
        }

        return(byteBuffer.ToBytes());
    }
예제 #2
0
    private byte[] PackProtocol(IMessage protocol, int addition = 0, List <int> player_id_list = null)
    {
        ByteBuffer buffer = new ByteBuffer();

        //写入附加位
        buffer.WriteInt(addition);

        //写入玩家ID列表
        if (player_id_list != null)
        {
            buffer.WriteInt(player_id_list.Count);
            foreach (int user_id in player_id_list)
            {
                buffer.WriteInt(user_id);
            }
        }
        else
        {
            buffer.WriteInt(0);
        }

        //写入协议体
        byte[] protocol_bytes = Protocol.Encode(protocol);
        buffer.WriteBytes(protocol_bytes);

        byte[] msg_bytes = buffer.ToBytes();
        buffer.Clear();
        buffer.WriteInt(msg_bytes.Length);
        buffer.WriteBytes(Encrypt.Encode(msg_bytes, Encrypt.DefaultKey));
        msg_bytes = buffer.ToBytes();
        buffer.Close();

        return(msg_bytes);
    }
예제 #3
0
    public ByteBuffer encode(IMessage obj)
    {
        ByteBuffer buff    = new ByteBuffer();
        int        protoId = GetProtoIdByType(obj.GetType());

        byte[] result;
        using (MemoryStream ms = new MemoryStream())
        {
            obj.WriteTo(ms);
            result = ms.ToArray();
        }

        UInt16 lengh = (UInt16)(result.Length + 2);

        Debug.Log("lengh" + lengh + ",protoId" + protoId);
        buff.WriteShort((UInt16)lengh);
        PrintBytes(buff.ToBytes());

        buff.WriteShort((UInt16)protoId);
        PrintBytes(buff.ToBytes());

        buff.WriteBytes(result);

        PrintBytes(buff.ToBytes());

        PrintBytes(result);

        return(buff);
    }
예제 #4
0
    private void AcceptClient(IAsyncResult ir)
    {
        TcpListener listener  = ir.AsyncState as TcpListener;
        TcpClient   tcpClient = listener.EndAcceptTcpClient(ir);
        //4.创建一个流用来收发数据
        NetworkStream stream = tcpClient.GetStream();

        //读入,也就是接受一个数据
        byte[]          data = new byte[1024];
        Login.RespLogin rsp  = new Login.RespLogin();
        rsp.isWin = true;
        rsp.level = 5;
        MemoryStream ms   = new MemoryStream();
        ByteBuffer   buff = new ByteBuffer();

        ProtoBuf.Meta.RuntimeTypeModel.Default.Serialize(ms, rsp);
        data = ms.ToArray();
        buff.WriteShort((ushort)ms.Length);
        buff.WriteShort((ushort)1002);
        buff.WriteBytes(data);
        stream.Write(buff.ToBytes(), 0, buff.ToBytes().Length);
        ms.Close();
        //5.关闭相应的流和监听器
        stream.Close();
        listener.BeginAcceptTcpClient(AcceptClient, listener);
    }
예제 #5
0
        public virtual byte[] GetBytes()
        {
            byte[] bodyData = GetBodyData();

            string uni   = Encoding.Unicode.GetString(bodyData);
            string ascii = Encoding.ASCII.GetString(bodyData);
            string utf8  = Encoding.UTF8.GetString(bodyData);

            byte[] tlvData = vTlv.GetBytes();
            int    length  = 16;

            length += bodyData == null ? 0 : bodyData.Length;
            length += tlvData == null ? 0 : tlvData.Length;
            vHeader.CommandLength = (uint)length;
            ByteBuffer buffer = new ByteBuffer(length); //Allocate buffer with enough capacity

            buffer.Append(vHeader.GetBytes());
            if (bodyData != null)
            {
                buffer.Append(bodyData);
            }
            if (tlvData != null)
            {
                buffer.Append(tlvData);
            }
            return(buffer.ToBytes());
        }
예제 #6
0
    public void HandleRegisterAccount(byte[] bytes, PlazaSession client)
    {
        string     id   = "";
        string     pw   = "";
        string     name = "";
        ByteBuffer read = new ByteBuffer(bytes);

        id   = read.ReadString();
        pw   = read.ReadString();
        name = read.ReadString();
        bool registerSucceed = false;

        if (id != string.Empty && pw != string.Empty && name == string.Empty)
        {
            registerSucceed = dataMgr.Register(id, pw, name);
        }
        string msg = "注册成功!";

        if (!registerSucceed)
        {
            msg = "注册失败!";
        }
        sessionCode.MainCmdId = 0;
        sessionCode.SubCmdId  = 1001;
        ByteBuffer buff = new ByteBuffer();

        buff.WriteString(msg);
        sessionCode.SetBytes(buff.ToBytes());
        byte[] byteCode = serial.Encode(sessionCode);
        SeverNet.instance.Send(client, byteCode);
    }
예제 #7
0
        private static void serverSendMessage(Socket clientSocket, string message)
        {
            ByteBuffer buffer = new ByteBuffer();

            buffer.WriteString(message);
            clientSocket.Send(WriteMessage(buffer.ToBytes()));
        }
예제 #8
0
    /// <summary>
    /// 发送消息给server
    /// </summary>
    /// <param name="datas"></param>
    public void SendMessage(int msgId, byte[] datas)
    {
        ByteBuffer writeBuffer = null;

        try
        {
            if (this.socket == null)
            {
                return;
            }

            writeBuffer = new ByteBuffer();

            writeBuffer.WriteInt(msgId);
            writeBuffer.WriteInt(datas.Length);
            writeBuffer.WriteBytes(datas);
            var sendBytes = writeBuffer.ToBytes();
            DebugLog(identiy, "send msg id : " + msgId + "  len: " + datas.Length);
            writeBuffer.Close();

            socket.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, new AsyncCallback(this.SendMessageCallBack), socket);
        }
        catch (Exception e)
        {
            if (writeBuffer != null)
            {
                writeBuffer.Close();
            }

            DoSocketException();

            DebugLogError(identiy, e.ToString());
        }
    }
예제 #9
0
    void Update()
    {
        if (sEvents.Count > 0)
        {
            while (sEvents.Count > 0)
            {
                KeyValuePair <int, ByteBuffer> _event = sEvents.Dequeue();
                int        msgID = _event.Key;
                ByteBuffer msg   = _event.Value;

                //处理C#中的网络回调
                if (m_CSharpCallback.ContainsKey(msgID))
                {
                    m_CSharpCallback[msgID](new MemoryStream(msg.ToBytes()));
                }
                //处理Lua中的网络回调
                else if (m_LuaCallback.ContainsKey(msgID))
                {
                    LuaNetCallback evt = m_LuaCallback[msgID];
                    //调用lua中的函数    形如: module.func(msg)
                    Util.CallMethod(evt.module, evt.func, msg);
                }
                else
                {
                    Log.Error("未处理的消息 : " + msgID);
                }
            }
        }
    }
예제 #10
0
        public void SendMsg(BodyMsg body, List <Socket> list = null)
        {
            MessageData data = new MessageData();
            HeadMsg     head = new HeadMsg();

            data.Head = head;
            data.Body = body;
            ByteBuffer _buff = new ByteBuffer();

            byte[] bytes = StaticTools.Serialize(data);
            _buff.WriteInt32(bytes.Length);
            _buff.WriteBytes(bytes);
            bytes = _buff.ToBytes();
            if (list == null)
            {
                list = GlobalData.GetAllPlayer();
            }
            foreach (var socket in list)
            {
                if (socket.Connected)
                {
                    socket.Send(bytes);
                }
            }
        }
예제 #11
0
    // 发送消息
    public void Send(ByteBuffer bytes, short nMessageID)
    {
        ByteBuffer temp = new ByteBuffer(bytes.ToBytes());

        byte[] buffer = temp.ReadBytes();
        m_clientSocket.Send(buffer, nMessageID);
    }
예제 #12
0
    /// <summary>
    /// 发送数据给服务器
    /// </summary>
    public void SendMessage(string data)
    {
        if (IsConnected == false)
        {
            return;
        }
        try
        {
            ByteBuffer buffer = new ByteBuffer();
            buffer.WriteString(data);
            clientSocket.Send(WriteMessage(buffer.ToBytes()));
            int receiveLength = clientSocket.Receive(result);

            ByteBuffer bufferBack = new ByteBuffer(result);
            int        len        = bufferBack.ReadShort();
            string     dataBack   = bufferBack.ReadString();
            Debug.Log("服务器返回数据:" + dataBack);
        }
        catch
        {
            IsConnected = false;
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
    }
예제 #13
0
파일: XDicom.cs 프로젝트: xiaotie/mdcm
        private static void LoadFragmentItem(XElement parent, DicomVR vr, ByteBuffer fragment)
        {
            XElement item = new XElement("item");

            item.SetAttributeValue("len", fragment.Length);
            parent.Add(item);

            if (vr == DicomVR.OW)
            {
                ushort[]      data = fragment.ToUInt16s();
                StringBuilder sb   = new StringBuilder();
                foreach (ushort d in data)
                {
                    sb.AppendFormat("{0:X4}\\", d);
                }
                item.Add(sb.ToString().TrimEnd('\\'));
            }
            else
            {
                byte[]        data = fragment.ToBytes();
                StringBuilder sb   = new StringBuilder();
                foreach (byte d in data)
                {
                    sb.AppendFormat("{0:X2}\\", d);
                }
                item.Add(sb.ToString().TrimEnd('\\'));
            }
        }
예제 #14
0
파일: SocketClient.cs 프로젝트: mengtest/wh
    /// <summary>
    /// 发送消息
    /// </summary>
    public void SendMessage(ByteBuffer buffer)
    {
        try
        {
            if (!isConnect)
            {
                Close();
                return;
            }

            //byte[] data=buffer.ToBytes();

            //foreach (byte b in data)
            //{
            //    Debug.Log("=============================================================");
            //    Debug.Log(b);  //法1
            //}

            WriteMessage(buffer.ToBytes());
            buffer.Close();
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
            AddExceptionMsg("Connect failed! SendMessage");
        }
    }
예제 #15
0
    /// <summary>
    /// 接收到消息
    /// startIndex:0 length:4
    /// MessageType startIndex:4 length:2
    /// ProtocalType startIndex:6 length:2
    /// BodyLength startIndex:8 length:4
    /// </summary>
    /// <param name="ms"></param>
    void OnReceivedMessage(MemoryStream ms, short protocal, short messageID, int bufLength)
    {
        BinaryReader r = new BinaryReader(ms);

        //if (protocal != Protocal.Heartbeat)
        //{
        //    Util.OtherLog("解析大厅消息,编号==================" + protocal);
        //}
        //移除超时
        Main.NetworkManager.RemoveTimeOut(socketType, messageID);

        byte[] oldBytes = r.ReadBytes((int)(ms.Length - ms.Position));
        byte[] newBytes = new byte[1024];
        //if (clientType == ClientType.Hall)
        //    newBytes = SecurityManager.Decrypt(protocal, oldBytes, AppConst.desHallKey);
        //else
        //    newBytes = SecurityManager.Decrypt(protocal, oldBytes, AppConst.desBt7Key);

        ByteBuffer buffer = new ByteBuffer();

        buffer.WriteBytes(oldBytes);
        ByteBuffer _buffer = new ByteBuffer(buffer.ToBytes());

        buffer.Close();
        Main.NetworkManager.AddEvent(socketType, protocal, _buffer);
    }
예제 #16
0
        /// <summary>
        /// 接收指定客户端Socket的消息
        /// </summary>
        /// <param name="clientSocket"></param>
        private static void RecieveMessage(object clientSocket)
        {
            Socket mClientSocket = (Socket)clientSocket;

            while (true)
            {
                try
                {
                    int receiveNumber = mClientSocket.Receive(result);
                    Console.WriteLine("接收客户端{0}消息, 长度为{1}", mClientSocket.RemoteEndPoint.ToString(), receiveNumber);
                    ByteBuffer buff = new ByteBuffer(result);
                    //数据长度
                    int len = buff.ReadShort();
                    //数据内容
                    string data = buff.ReadString();
                    Console.WriteLine("数据内容:{0}", data);

                    ByteBuffer buffer = new ByteBuffer();
                    buffer.WriteString(data);
                    mClientSocket.Send(WriteMessage(buffer.ToBytes()));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    mClientSocket.Shutdown(SocketShutdown.Both);
                    mClientSocket.Close();
                    break;
                }
            }
        }
예제 #17
0
        private void DispathProtoMessageEvent(int protoEvent, ByteBuffer buffer)
        {
            if (protoEvent != Protocal.Message)
            {
                return;
            }

            int    protoId   = buffer.ReadShort();
            string protoName = "";

            if (!NetworkManager.Instance.ProtoConfigDic.TryGetValue(protoId, out protoName))
            {
                ConsoleView.LogError("<<ConsoleView,DispathProtoEvent>> 没有找到协议!protoId:" + protoId);
                return;
            }

            Type loginReq = this.mainForm.ProtoView.GetProtoType(protoName);

            if (loginReq == null)
            {
                ConsoleView.LogError("<<ConsoleView,DispathProtoEvent>> 没有找到协议!" + protoName);
                return;
            }

            MethodInfo deserializeMethod = loginReq.GetMethod("Deserialize", BindingFlags.Public | BindingFlags.Static);
            object     obj  = deserializeMethod.Invoke(null, new[] { buffer.ToBytes() });
            string     json = LitJson.JsonMapper.ToJson(obj);

            Console.WriteLine(json);
        }
		/// <summary>
		/// Get a byte array for the frame's data.
		/// </summary>
		/// <returns></returns>
		public byte[] GetByteArray()
		{
			if (_reference != null)
				return Load().ToBytes();

			return _bb.ToBytes();
		}
예제 #19
0
    public byte[] GameObjectsToBytes()
    {
        ByteBuffer byteBuffer = new ByteBuffer();

        if (!allGameObjectInfos.Contains(terrainInfo))
        {
            allGameObjectInfos.Add(terrainInfo);
        }
        GameObjectInfo gameObjectInfo = null;

        Byte[] bytes;
        int    length = allGameObjectInfos.Count;

        byteBuffer.WriteUShort((ushort)(length));

        for (int i = 0; i < length; ++i)
        {
            gameObjectInfo = allGameObjectInfos[i];
            bytes          = gameObjectInfo.ToBytes();
            byteBuffer.WriteInt(bytes.Length);
            byteBuffer.WriteBytes(bytes);
        }
        allGameObjectInfos.Remove(terrainInfo);
        return(byteBuffer.ToBytes());
    }
예제 #20
0
        public void SendMsg(int cmd, int scmd, ByteBuffer buffer, List <Client> _users = null)
        {
            MessageData sendMsg = new MessageData();
            HeadMsg     head    = new HeadMsg();

            head.cmd     = cmd;
            head.scmd    = scmd;
            sendMsg.head = head;
            sendMsg.data = buffer.ToBytes();
            byte[]     bytes      = ProtoBufTools.Serialize(sendMsg);
            ByteBuffer sendBuffer = new ByteBuffer();

            sendBuffer.WriteInt32(bytes.Length);
            sendBuffer.WriteBytes(bytes);
            bytes = sendBuffer.ToBytes();
            if (_users == null)
            {
                _users = GlobalData.GetUsersAllClient();
            }
            foreach (var socket in _users)
            {
                if (socket.Connected)
                {
                    socket.socket.Send(bytes);
                }
            }
        }
예제 #21
0
    public void SendMessage(short protocal, short messageID, byte[] buf, string key)
    {
        //if (protocal != Protocal.Heartbeat)
        //{
        //    Util.Log("发送大厅消息,编号=========== " + protocal);
        //}
        // 加密
        ByteBuffer buffer = new ByteBuffer();

        buffer.WriteShort(protocal);
        buffer.WriteShort(messageID);
        if (buf != null)
        {
            //buffer.WriteBytes(SecurityManager.Encrypt(protocal, buf, key));   //加密
            buffer.WriteBytes(buf);
        }
        else
        {
            buffer.WriteInt(0);
        }

        byte[] bytes = buffer.ToBytes();
        WriteMessage(bytes, messageID, protocal);
        buffer.Close();
    }
예제 #22
0
        private void SaveServerFileListToPersistent()
        {
            string filePath = PathUtility.GetCombinePath(AppConst.Path.PresistentDataPath,
                                                         AppConst.AssetBundleConfig.FileListFile);

            if (newFileInfoTable.Count > 0)
            {
                using (ByteBuffer buffer = new ByteBuffer())
                {
                    ValueParse.WriteValue(buffer, newFileInfoTable.Count, ValueParse.IntParse);
                    foreach (KeyValuePair <string, UpdateFileInfo> updateFileInfo in newFileInfoTable)
                    {
                        ValueParse.WriteValue(buffer, updateFileInfo.Value.AssetBundleName, ValueParse.StringParse);
                        ValueParse.WriteValue(buffer, updateFileInfo.Value.Length, ValueParse.IntParse);
                        ValueParse.WriteValue(buffer, updateFileInfo.Value.Md5Code, ValueParse.IntParse);
                        ValueParse.WriteValue(buffer, updateFileInfo.Value.ZipLength, ValueParse.IntParse);
                        ValueParse.WriteValue(buffer, updateFileInfo.Value.ZipMd5Code, ValueParse.IntParse);
                    }
                    if (FileUtility.IsFileExist(filePath))
                    {
                        FileUtility.DeleteFile(filePath);
                    }
                    File.WriteAllBytes(filePath, buffer.ToBytes());
                }
            }
        }
예제 #23
0
        private void SaveServerVersionToPersistent()
        {
            string filePath = PathUtility.GetCombinePath(AppConst.Path.PresistentDataPath,
                                                         AppConst.AssetBundleConfig.VersionFile);

            using (ByteBuffer buffer = new ByteBuffer())
            {
                ValueParse.WriteValue(buffer, platform.ToString(), ValueParse.StringParse);
                ValueParse.WriteValue(buffer, serverVersion.MasterVersion, ValueParse.IntParse);
                ValueParse.WriteValue(buffer, serverVersion.MinorVersion, ValueParse.IntParse);
                ValueParse.WriteValue(buffer, serverVersion.RevisedVersion, ValueParse.IntParse);
                ValueParse.WriteValue(buffer, 0, ValueParse.IntParse);
                ValueParse.WriteValue(buffer, 0, ValueParse.LongParse);
                ValueParse.WriteValue(buffer,
                                      string.IsNullOrEmpty(Singleton <GameEntry> .GetInstance().GetComponent <ResourceComponent>()
                                                           .AssetBundleVariant)
                        ? ""
                        : Singleton <GameEntry> .GetInstance().GetComponent <ResourceComponent>().AssetBundleVariant,
                                      ValueParse.StringParse);
                ValueParse.WriteValue(buffer, true, ValueParse.BoolParse);
                ValueParse.WriteValue(buffer, "", ValueParse.StringParse);
                if (FileUtility.IsFileExist(filePath))
                {
                    FileUtility.DeleteFile(filePath);
                }
                File.WriteAllBytes(filePath, buffer.ToBytes());
            }
        }
예제 #24
0
    /// <summary>
    /// 发送数据给服务器
    /// </summary>
    public void SendMessage(string data, string cbName, MsgDistribution.Delegate cb)
    {
        ByteBuffer buffer = new ByteBuffer();

        buffer.WriteString(data);
        byte[] msg = WriteMessage(buffer.ToBytes());
        SendMessage(msg, cbName, cb);
    }
예제 #25
0
    /// <summary>
    /// 发送数据给服务器
    /// </summary>
    public void SendMessage(string data)
    {
        ByteBuffer buffer = new ByteBuffer();

        buffer.WriteString(data);
        byte[] msg = WriteMessage(buffer.ToBytes());
        SendMessage(msg);
    }
예제 #26
0
        protected override byte[] GetBodyData()
        {
            ByteBuffer buffer = new ByteBuffer(vSystemID.Length + vPassword.Length + 2);

            buffer.Append(EncodeCString(vSystemID));
            buffer.Equals(EncodeCString(vPassword));
            return(buffer.ToBytes());
        }
예제 #27
0
    public void SendMessage(string str_protoId, ByteBuffer buffer)
    {
        byte[] data    = buffer.ToBytes();
        int    protoId = int.Parse(str_protoId.Trim());

        Debug.LogError(protoId + ":" + data.Length);
        m_clientSocket.Send(data, protoId);
    }
예제 #28
0
        protected override byte[] GetBodyData()
        {
            ByteBuffer buffer = new ByteBuffer(16);

            buffer.Append(EncodeCString(vMessageID));
            buffer.Append(vSourceAddress.GetBytes());
            return(buffer.ToBytes());
        }
예제 #29
0
    void sendMsgFloat(int id, float msg)
    {
        ByteBuffer buffer = new ByteBuffer();

        buffer.WriteInt(id);
        buffer.WriteFloat(msg);
        client.Send(buffer.ToBytes());
    }
예제 #30
0
    void sendMsgString(int id, string msg)
    {
        ByteBuffer buffer = new ByteBuffer();

        buffer.WriteInt(id);
        buffer.WriteString(msg);
        client.Send(buffer.ToBytes());
    }
예제 #31
0
 public void SendMessage(ByteBuffer buffer)
 {
     Debug.Log(buffer.ToBytes());
     SocketClient.SendMessage(buffer);
 }
예제 #32
0
 /// <summary>
 /// 发送消息
 /// </summary>
 public void SendMessage(ByteBuffer buffer)
 {
     SessionSend(buffer.ToBytes());
     buffer.Close();
 }