Unity3D中的Socket通信

来源:互联网 发布:淘宝上好吃的蛋糕店 编辑:程序博客网 时间:2024/05/16 08:49

设计为四个部分,第一部分接收发送数据,第二部分本地数据转换为字节发送到服务器包括发送包长度,包头,加密,具体内容等.第三部分接收byte转换为数据.第四部分监听.


第一部分简单示例:连接服务器Ip 端口,发送请求,接收数据同理.


  1. public static void SocketConnect(string serverIP, int serverPort)
  2.     {
  3.         clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  4.         IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
  5.         try
  6.         {
  7.             clientSocket.Connect(ipe);
  8.             Debug.Log(" Connect Success IP: " + serverIP + " Port : " + serverPort.ToString());
  9.         }
  10.         catch (Exception e)
  11.         {
  12.             Debug.LogError(e.ToString());
  13.         }
  14.     }
  15.     //发送数据
  16.     public static void Send(byte[] bytes)
  17.     {
  18.         if (clientSocket == null)
  19.             return;
  20.         if (!clientSocket.Connected)
  21.             return;
  22.         if (clientSocket.Poll(0, SelectMode.SelectWrite))
  23.         {
  24.             try
  25.             {
  26.                 clientSocket.Send(bytes);
  27.             }
  28.             catch (Exception e)
  29.             {
  30.                 Debug.LogError(e.ToString());
  31.             }
  32.         }
  33.     }
复制代码
第二部分请求数据示例:
  1. public void _MSG_ACCOUNT(string name, string pwd)
  2.     {
  3.         ACCOUNT account = new ACCOUNT();
  4.         datas = new byte[account.length];
  5.         byte[] bytesLength = BitConverter.GetBytes((System.Int16)account.length);
  6.         int length = 0;
  7.         bytesLength.CopyTo(datas, length);
  8.         length += 2;
  9.         byte[] bytesID = BitConverter.GetBytes((System.Int16)account.ID);
  10.         bytesID.CopyTo(datas, length);
  11.         length += 2;
  12.         byte[] bytesName = Encoding.Default.GetBytes(name);
  13.         bytesName.CopyTo(datas, length);
复制代码
第三部分接收数据示例:
  1. void _MSG_CONNECT(byte[] datas)
  2.     {

  3.         connect = new CONNECT();
  4.         int length = 4;
  5.         connect.idAccount = BitConverter.ToUInt32(datas, length);
  6.         Debug.LogError("账号ID          " + connect.idAccount);

  7.         length += System.Runtime.InteropServices.Marshal.SizeOf(connect.idAccount);
  8.         connect.dwData = BitConverter.ToUInt32(datas, length);
  9.         Debug.LogError("认证ID            " + connect.dwData);

  10.         length += System.Runtime.InteropServices.Marshal.SizeOf(connect.dwData);
  11.         connect.nServerIndex = BitConverter.ToUInt32(datas, length);
  12.         Debug.LogError("游戏逻辑服务器索引           " + connect.nServerIndex);
复制代码
运行效果:


1.png
原创粉丝点击