自定义协议方法

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

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

你可能感兴趣的:(自定义协议方法)