Unity问答

Unity3D中的Socket通信

Posted on 2013年06月24日 by U3d / Unity3D脚本/插件 /被围观 1,901 次

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

   
01
    public static void SocketConnect(string serverIP, int serverPort)  
02
        {  
03
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
04
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);  
05
            try  
06
            {  
07
                clientSocket.Connect(ipe);  
08
                Debug.Log(" Connect Success IP: " + serverIP + " Port : " + serverPort.ToString());  
09
            }  
10
            catch (Exception e)  
11
            {  
12
                Debug.LogError(e.ToString());  
13
            }  
14
        }  //Unity3D教程手册:www.manew.com
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
        }  

第二部分请求数据示例:

   
01
  public void _MSG_ACCOUNT(string name, string pwd)  
02
       {  
03
           ACCOUNT account = new ACCOUNT();  
04
           datas = new byte[account.length];  
05
           byte[] bytesLength = BitConverter.GetBytes((System.Int16)account.length);  
06
           int length = 0;  
07
           bytesLength.CopyTo(datas, length);  
08
           length += 2;  
09
           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);  

第三部分接收数据示例:

   
01
    void _MSG_CONNECT(byte[] datas)  
02
        {  
03
 
04
            connect = new CONNECT();  
05
            int length = 4;  
06
            connect.idAccount = BitConverter.ToUInt32(datas, length);  
07
            Debug.LogError("账号ID          " + connect.idAccount);  
08
            //Unity3D教程手册:www.manew.com
09
            length += System.Runtime.InteropServices.Marshal.SizeOf(connect.idAccount);  
10
            connect.dwData = BitConverter.ToUInt32(datas, length);  
11
            Debug.LogError("认证ID            " + connect.dwData);  
12
 
13
            length += System.Runtime.InteropServices.Marshal.SizeOf(connect.dwData);  
14
            connect.nServerIndex = BitConverter.ToUInt32(datas, length);  
15
            Debug.LogError("游戏逻辑服务器索引           " + connect.nServerIndex);  

运行效果:

Unity3D中的Socket通信

Unity3D中的Socket通信

Unity3D中的Socket通信:等您坐沙发呢!

发表评论