Unity3D中的Socket通信——转自悟之思语

设计为四个部分,第一部分接收发送数据,第二部分本地数据转换为字节发送到服务器包括发送包长度,包头,加密,具体内容等.第三部分接收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);
  13. 转载连接:http://blog.csdn.net/jbjwpzyl3611421/article/details/11111359
posted @ 2017-06-05 14:45  一颗菜的成长史  阅读(133)  评论(0)    收藏  举报