Unity Socket 交互编程

本文展示了如何在Unity中使用C#实现Socket网络编程,包括客户端和服务器端的代码实现,用于连接和断开与服务器的交互。通过UnitySocket类,实现了发送和接收各种类型的数据,如字符串、整数、浮点数等。代码中包含连接、断开、登录和关闭连接的功能,适合初学者理解Unity中的网络通信基础。
摘要由CSDN通过智能技术生成
这几天研究了下Socket交互。
    通过网上的资料做了有关Socket的第一个Demo,虽然不是很成熟,但个人感觉已经相对比较完整了。各类型数据的传输接受都有,其中也做了float类型的(因为我感觉做Unity应该用的着)。
    功能方面,为了测试多用户交互,我在Demo上开启了4个Socket 4个线程接受数据。实现了服务端通知用户进入 离开功能。
    真机上,需要加上字库,要不无法显示中文。
   
    工程目录:

 

    下面上代码:

客户端代码:

  1. using UnityEngine;  
  2. using System;  
  3. using System.Collections;  
  4. using LSocket.Net;  
  5. using LSocket.Type;  
  6. using LSocket.cmd;  
  7.   
  8.    public class SocketDemo : MonoBehaviour  
  9.    {  
  10.        public UnitySocket[] socket;  
  11.        public String[] textAreaString;  
  12.        public String[] textFieldString;  
  13.        public GUISkin mySkin;  
  14.        // Use this for initialization   
  15.        void Start()  
  16.        {  
  17.            socket = new UnitySocket[4];  
  18.            textAreaString = new String[12];  
  19.            for (int i = 0; i < 12; i++)  
  20.            {  
  21.                textAreaString[i] = "";  
  22.            }  
  23.            textFieldString = new String[4];  
  24.            for(int i=0;i<4;i++){  
  25.                textFieldString[i] = "";  
  26.            }  
  27.        }  
  28.   
  29.        // Update is called once per frame   
  30.        void Update()  
  31.        {  
  32.   
  33.        }  
  34.   
  35.        void OnGUI()  
  36.        {  
  37.            GUI.skin = mySkin;  
  38.            for (int i = 0; i < 4; i++)  
  39.            {  
  40.                String s = textAreaString[i * 3] + "\n" + textAreaString[i * 3 + 1] + "\n" + textAreaString[i * 3 + 2];  
  41.                GUI.TextArea(new Rect(i % 2 * Screen.width / 2, i / 2 * (Screen.height / 2) + 50, 100, 60), s);  
  42.                textFieldString[i] = GUI.TextField(new Rect(i % 2 * Screen.width / 2+50, i / 2 * (Screen.height / 2), 100, 20), textFieldString[i]);  
  43.                if (GUI.Button(new Rect(i % 2 * Screen.width / 2, i / 2 * (Screen.height / 2), 40, 20), "连接"))  
  44.                {  
  45.                    socket[i] = null;  
  46.                    socket[i] = new UnitySocket();  
  47.                    socket[i].SocketConnection("192.168.0.8", 10000, this, i);  
  48.                    socket[i].DoLogin(textFieldString[i]);  
  49.                }  
  50.                else if (GUI.Button(new Rect(i % 2 * Screen.width / 2, i / 2 *( Screen.height / 2) + 25, 40, 20), "关闭"))  
  51.                {  
  52.                    if (socket[i] != null)  
  53.                    {  
  54.                        socket[i].close();  
  55.                        socket[i] = null;  
  56.                    }  
  57.                }  
  58.            }  
  59.   
  60.            if (GUI.Button(new Rect(Screen.width - 60, Screen.height - 30, 60, 30), "退出")) {  
  61.                Application.Quit();  
  62.            }  
  63.   
  64.        }  
  65.    }  
 using UnityEngine;
 using System;
 using System.Collections;
 using LSocket.Net;
 using LSocket.Type;
 using LSocket.cmd;

    public class SocketDemo : MonoBehaviour
    {
        public UnitySocket[] socket;
        public String[] textAreaString;
        public String[] textFieldString;
        public GUISkin mySkin;
        // Use this for initialization
        void Start()
        {
            socket = new UnitySocket[4];
            textAreaString = new String[12];
            for (int i = 0; i < 12; i++)
            {
                textAreaString[i] = "";
            }
            textFieldString = new String[4];
            for(int i=0;i<4;i++){
                textFieldString[i] = "";
            }
        }

        // Update is called once per frame
        void Update()
        {

        }

        void OnGUI()
        {
            GUI.skin = mySkin;
            for (int i = 0; i < 4; i++)
            {
                String s = textAreaString[i * 3] + "\n" + textAreaString[i * 3 + 1] + "\n" + textAreaString[i * 3 + 2];
                GUI.TextArea(new Rect(i % 2 * Screen.width / 2, i / 2 * (Screen.height / 2) + 50, 100, 60), s);
                textFieldString[i] = GUI.TextField(new Rect(i % 2 * Screen.width / 2+50, i / 2 * (Screen.height / 2), 100, 20), textFieldString[i]);
                if (GUI.Button(new Rect(i % 2 * Screen.width / 2, i / 2 * (Screen.height / 2), 40, 20), "连接"))
                {
                    socket[i] = null;
                    socket[i] = new UnitySocket();
                    socket[i].SocketConnection("192.168.0.8", 10000, this, i);
                    socket[i].DoLogin(textFieldString[i]);
                }
                else if (GUI.Button(new Rect(i % 2 * Screen.width / 2, i / 2 *( Screen.height / 2) + 25, 40, 20), "关闭"))
                {
                    if (socket[i] != null)
                    {
                        socket[i].close();
                        socket[i] = null;
                    }
                }
            }

            if (GUI.Button(new Rect(Screen.width - 60, Screen.height - 30, 60, 30), "退出")) {
                Application.Quit();
            }

        }
    }



 

  1. namespace LSocket.Net   
  2. /** 
  3.  *  
  4.  * @author feng侠,qq:313785443 
  5.  * @date 2010-12-23 
  6.  * 
  7.  */  
  8.   
  9.     // 描   述:封装c# socket数据传输协议    
  10.     using UnityEngine;   
  11.     using System;   
  12.     using System.Net.Sockets;   
  13.     using System.Net;   
  14.     using System.Collections;   
  15.     using System.Text;  
  16.     using System.Threading;  
  17.     using LSocket.Type;   
  18.     using LSocket.cmd;  
  19.   
  20.   
  21.     class SocketThread  
  22.     {  
  23.   
  24.         UnitySocket socket;  
  25.         SocketDemo demo;  
  26.         int idx;  
  27.   
  28.         public SocketThread(UnitySocket socket, SocketDemo demo, int idx)  
  29.         {  
  30.             this.socket = socket;  
  31.             this.demo = demo;  
  32.             this.idx = idx;  
  33.         }  
  34.   
  35.         public void run()  
  36.         {  
  37.             while (true)  
  38.             {  
  39.                 try  
  40.                 {  
  41.                     String s = socket.ReceiveString();  
  42.                     demo.textAreaString[idx * 3] = demo.textAreaString[idx * 3 + 1];  
  43.                     demo.textAreaString[idx * 3 + 1] = demo.textAreaString[idx * 3 + 2];  
  44.                     demo.textAreaString[idx * 3 + 2] = s;  
  45.                     MonoBehaviour.print(s + " " + idx);  
  46.                 }  
  47.                 catch (Exception e)  
  48.                 {  
  49.                     MonoBehaviour.print(e.ToString());  
  50.                     socket.t.Abort();  
  51.                 }  
  52.             }  
  53.         }  
  54.   
  55.     }  
  56.   
  57.     public class UnitySocket   
  58.     {   
  59.         public Socket mSocket = null;  
  60.         public Thread t=null;  
  61.         private SocketThread st=null;  
  62.         public SocketDemo demo=null;  
  63.   
  64.         public UnitySocket()   
  65.         {   
  66.                
  67.         }   
  68.         public void SocketConnection(string LocalIP, int LocalPort,SocketDemo demo,int idx)   
  69.         {  
  70.             this.demo=demo;  
  71.             mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);   
  72.             try   
  73.             {   
  74.                    
  75.                 IPAddress ip = IPAddress.Parse(LocalIP);   
  76.                 IPEndPoint ipe = new IPEndPoint(ip, LocalPort);   
  77.                 mSocket.Connect(ipe);  
  78.                 st =new SocketThread(this, demo, idx);  
  79.                 t = new Thread(new ThreadStart(st.run));  
  80.                 t.Start();  
  81.             }   
  82.             catch (Exception e)   
  83.             {  
  84.                 MonoBehaviour.print(e.ToString());  
  85.             }   
  86.         }  
  87.           
  88.         public void close(){  
  89.             mSocket.Close(0);  
  90.             mSocket=null;  
  91.         }  
  92.   
  93.         public void DoLogin(String userName){  
  94.             try  
  95.             {  
  96.                 Send(CommandID.LOGIN);  
  97.                 Send(userName);  
  98.             }catch(Exception e){  
  99.                 MonoBehaviour.print(e.ToString());  
  100.             }  
  101.         }  
  102.   
  103.   
  104.         public void Send(float data){  
  105.             byte[] longth = TypeConvert.getBytes(data, true);  
  106.             mSocket.Send(longth);  
  107.         }  
  108.   
  109.         public float ReceiveFloat()  
  110.         {  
  111.             byte[] recvBytes = new byte[4];  
  112.             mSocket.Receive(recvBytes, 4, 0);//从服务器端接受返回信息    
  113.             float data = TypeConvert.getFloat(recvBytes, true);  
  114.             return data;  
  115.         }   
  116.   
  117.         public void Send(short data)   
  118.         {   
  119.             byte[] longth=TypeConvert.getBytes(data,true);   
  120.             mSocket.Send(longth);  
  121.         }   
  122.            
  123.         public void Send(long data)   
  124.         {   
  125.             byte[] longth=TypeConvert.getBytes(data,true);   
  126.             mSocket.Send(longth);   
  127.         }   
  128.            
  129.         public void Send(int data)   
  130.         {   
  131.             byte[] longth=TypeConvert.getBytes(data,true);   
  132.             mSocket.Send(longth);   
  133.                
  134.         }   
  135.            
  136.         public void Send(string data)   
  137.         {   
  138.             byte[] longth=Encoding.UTF8.GetBytes(data);  
  139.             Send(longth.Length);  
  140.             mSocket.Send(longth);   
  141.           
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值