C#使用Protocol Buffer(ProtoBuf)进行Unity中的Socket通信

2019-12-30 12:23:35于海丽

 

在Unity中开启服务器,并使用C#控制台模拟客户端连接、发送消息操作。测试OK了,Unity中可以时时监听到消息。


using UnityEngine;
using System.Collections;

public class CreateServer : MonoBehaviour {

 void StartServer () {
  NetServer.Instance.Start();
 }

}

//C#控制台工程

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;

namespace Temp
{
 class MainClass
 {
  public static void Main (string[] args)
  {
   TcpClient tc = new TcpClient();
   IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 35353);
   tc.Connect(ip);

   if(tc.Connected)
   {
    while(true)
    {

     string msg = Console.ReadLine();
     byte[] result = Encoding.UTF8.GetBytes(msg);
     tc.GetStream().Write(result, 0, result.Length);
    }
   }
   Console.ReadLine();
  }
 }
}

using UnityEngine;
using System.Collections;
 
public class CreateServer : MonoBehaviour {
 
 void StartServer () {
  NetServer.Instance.Start();
 }
 
}
 
//C#控制台工程
 
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
 
namespace Temp
{
 class MainClass
 {
  public static void Main (string[] args)
  {
   TcpClient tc = new TcpClient();
   IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 35353);
   tc.Connect(ip);
 
   if(tc.Connected)
   {
    while(true)
    {
 
     string msg = Console.ReadLine();
     byte[] result = Encoding.UTF8.GetBytes(msg);
     tc.GetStream().Write(result, 0, result.Length);
    }
   }
   Console.ReadLine();
  }
 }
}

三、数据包的编码和解码

首先,举个例子,这个月信用卡被媳妇刷爆了,面对房贷车贷的压力,我只能选择分期付款。。。

那么OK了,现在我想问一下,当服务器向客户端发送的数据过大时怎么办呢?

当服务器需要向客户端发送一条很长的数据,也会“分期付款!”,服务器会把一条很长的数据分成若干条小数据,多次发送给客户端。

可是,这样就又有另外一个问题,客户端接受到多条数据之后如何解析?

这里其实就是客户端的解码。server发数据一般采用“长度+内容”的格式,Client接收到数据之后,先提取出长度来,然后根据长度判断内容是否发送完毕。

再次重申,用户在发送序列化好的消息的前,需要先编码后再发送消息;用户在接受消息后,需要解码之后再解析数据(反序列化)。


using UnityEngine;
using System.Collections.Generic;
using System.IO;

// 编码和解码
public class NetEncode {

 // 将数据编码 长度+内容
 /// < param name="data">内容< /param>
 public static byte[] Encode(byte[] data)
 {
  //整形占四个字节,所以声明一个+4的数组
  byte[] result = new byte[data.Length + 4];
  //使用流将编码写二进制
  MemoryStream ms = new MemoryStream();
  BinaryWriter br = new BinaryWriter(ms);
  br.Write(data.Length);
  br.Write(data);
  //将流中的内容复制到数组中
  System.Buffer.BlockCopy(ms.ToArray(), 0, result, 0, (int)ms.Length);
  br.Close();
  ms.Close();
  return result;
 }

 // 将数据解码
 // < param name="cache">消息队列< /param>
 public static byte[] Decode(ref List<byte> cache)
 {
  //首先要获取长度,整形4个字节,如果字节数不足4个字节
  if(cache.Count < 4)
  {
   return null;
  }
  //读取数据
  MemoryStream ms = new MemoryStream(cache.ToArray());
  BinaryReader br = new BinaryReader(ms);
  int len = br.ReadInt32();
  //根据长度,判断内容是否传递完毕
  if(len > ms.Length - ms.Position)
  {
   return null;
  }
  //获取数据
  byte[] result = br.ReadBytes(len);
  //清空消息池
  cache.Clear();
  //讲剩余没处理的消息存入消息池
  cache.AddRange(br.ReadBytes((int)ms.Length - (int)ms.Position));

  return result;
 }
}

using UnityEngine;
using System.Collections.Generic;
using System.IO;
 
// 编码和解码
public class NetEncode {
 
 // 将数据编码 长度+内容
 /// < param name="data">内容< /param>
 public static byte[] Encode(byte[] data)
 {
  //整形占四个字节,所以声明一个+4的数组
  byte[] result = new byte[data.Length + 4];
  //使用流将编码写二进制
  MemoryStream ms = new MemoryStream();
  BinaryWriter br = new BinaryWriter(ms);
  br.Write(data.Length);
  br.Write(data);
  //将流中的内容复制到数组中
  System.Buffer.BlockCopy(ms.ToArray(), 0, result, 0, (int)ms.Length);
  br.Close();
  ms.Close();
  return result;
 }
 
 // 将数据解码
 // < param name="cache">消息队列< /param>
 public static byte[] Decode(ref List<byte> cache)
 {
  //首先要获取长度,整形4个字节,如果字节数不足4个字节
  if(cache.Count < 4)
  {
   return null;
  }
  //读取数据
  MemoryStream ms = new MemoryStream(cache.ToArray());
  BinaryReader br = new BinaryReader(ms);
  int len = br.ReadInt32();
  //根据长度,判断内容是否传递完毕
  if(len > ms.Length - ms.Position)
  {
   return null;
  }
  //获取数据
  byte[] result = br.ReadBytes(len);
  //清空消息池
  cache.Clear();
  //讲剩余没处理的消息存入消息池
  cache.AddRange(br.ReadBytes((int)ms.Length - (int)ms.Position));
 
  return result;
 }
}