美文网首页
自定义协议方法

自定义协议方法

作者: Pomelo的笔记本 | 来源:发表于2017-04-28 19:04 被阅读0次

    发送消息实现聊天功能的通讯字节流协议

    private byte[] SendAgreement1106(string str)
    {
      //设置该协议的id为1106
      byte[] id = BitConverter.GetBytes(1106);
      //将内容string转为流数据byte[]
      byte[] body = System.Text.Encoding.UTF8.GetBytes(str);
      //取得协议id和内容的流数据长度和,作为包头
      byte[] length = BitConverter.GetBytes(id.Length + body.Length);
      //unity的控制台输出
      Debug.Log("协议长度【" + id.Length + "】内容长度【" + body.Length 
                      + "】总长度【" + id.Length + body.Length + "】");
      //新建流数据对象,长度=协议长度+内容长度+包头长度
      byte[] send = new byte[id.Length + body.Length + sizeof(Int32)];
      //将各流数据打包成一个数据包
      //包头
      Array.Copy(length, 0, send, 0, sizeof(Int32));
      //协议
      Array.Copy(id, 0, send, sizeof(Int32), sizeof(Int32));
      //内容
      Array.Copy(body, 0, send, 2 * sizeof(Int32), body.Length);
      //返回要发送的数据包对象
      return send;
    }
    

    接受数据、分析协议

    private void AgreementAnalysis(byte[] receive)
        {
            //若数据包长度小于包头的长度,则返回
            if (receive.Length < sizeof(Int32))
                return;
            //若数据包长度小于包头说明的长度,则返回
            if (receive.Length + sizeof(Int32) < BitConverter.ToInt32(receive, 0))
                return;   
            //获得协议id       
            int id = BitConverter.ToInt32(receive, 4);
            switch (id)
            {
                case 1106:
                    ReceiveAgreement1106(receive);
                    break;
            }
        }
        private void ReceiveAgreement1106(byte[] reveive)
        {
            Debug.Log("接受:" + System.Text.Encoding.UTF8.GetString(receive,
                        sizeof(Int32) * 2, receive.Length - 2 * sizeof(Int32)));
            //return System.Text.Encoding.UTF8.GetString(receive, sizeof(Int32) * 2, 
                        //receive.Length - 2*sizeof(Int32));
        }
    
    控制台发送和接受的内容.jpg

    相关文章

      网友评论

          本文标题:自定义协议方法

          本文链接:https://www.haomeiwen.com/subject/ubsazttx.html