unity使用socket通讯
认识socket
在计算机通信领域,socket 被翻译为“套接字”,它是计算机之间进行通信的一种约定或一种方式。通过 socket 这种约定,一台计算机可以接收其他计算机的数据,也可以向其他计算机发送数据socket起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,都可以用“打开open –> 读写write/read –> 关闭close”模式来操作。我的理解就是Socket就是该模式的一个实现:即socket是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO、打开、关闭)。Socket()函数返回一个整型的Socket描述符,随后的连接建立、数据传输等操作都是通过该Socket实现的。
实现socket通讯,需要两个部分才能进行数据通讯。
1,客户端请求连接
2,服务器响应
服务端
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using System.Net.Sockets;//需要引用socket命名空间 5 using System.Net; 6 using System.Linq; 7 using System.Text; 8 using System.Threading; 9 10 public class net : MonoBehaviour 11 { 12 // Start is called before the first frame update 13 void Start() 14 { 15 openServer(); 16 } 17 18 // Update is called once per frame 19 void Update() 20 { 21 22 } 23 24 /// <summary> 25 /// 打开链接 26 /// </summary> 27 void openServer() 28 { 29 try 30 { 31 IPAddress pAddress = IPAddress.Parse("127.0.0.1"); 32 IPEndPoint pEndPoint = new IPEndPoint(pAddress, 52315); 33 Socket socket_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 34 socket_server.Bind(pEndPoint); 35 socket_server.Listen(5);//设置最大连接数 36 Debug.Log("监听成功"); 37 //创建新线程执行监听,否则会阻塞UI,导致unity无响应 38 Thread thread = new Thread(listen); 39 thread.IsBackground = true; 40 thread.Start(socket_server); 41 } 42 catch (System.Exception) 43 { 44 45 throw; 46 } 47 } 48 /// <summary> 49 /// 监听 50 /// </summary> 51 Socket socketSend; 52 void listen(object o) 53 { 54 try 55 { 56 Socket socketWatch = o as Socket; 57 while (true) 58 { 59 socketSend = socketWatch.Accept(); 60 Debug.Log(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功"); 61 62 Thread r_thread = new Thread(Received); 63 r_thread.IsBackground = true; 64 r_thread.Start(socketSend); 65 } 66 } 67 catch (System.Exception) 68 { 69 70 throw; 71 } 72 } 73 /// <summary> 74 /// 获取消息 75 /// </summary> 76 /// <param name="o"></param> 77 void Received(object o) 78 { 79 try 80 { 81 Socket socketSend = o as Socket; 82 while (true) 83 { 84 byte[] buffer = new byte[1024]; 85 int len = socketSend.Receive(buffer); 86 if (len == 0) break; 87 string str = Encoding.UTF8.GetString(buffer, 0, len); 88 Debug.Log("服务器打印客户端返回消息:" + socketSend.RemoteEndPoint + ":" + str); 89 Send("我收到了"); 90 } 91 } 92 catch (System.Exception) 93 { 94 95 throw; 96 } 97 } 98 /// <summary> 99 /// 发送消息 100 /// </summary> 101 /// <param name="msg"></param> 102 void Send(string msg) 103 { 104 byte[] buffer = Encoding.UTF8.GetBytes(msg); 105 socketSend.Send(buffer); 106 } 107 }
客户端
1 using UnityEngine; 2 using UnityEngine.UI; 3 using System.Net; 4 using System.Net.Sockets;//引入socket命名空间 5 using System.Threading; 6 using System.Text; 7 using UnityEngine.SceneManagement; 8 9 public class net : MonoBehaviour 10 { 11 //添加两个按钮用于发送数据和关闭连接 12 public Button sen; 13 public Button col; 14 //输入文本 15 public InputField inputText; 16 // Start is called before the first frame update 17 void Start() 18 { 19 sen.onClick.AddListener(send_smg);//发送 20 col.onClick.AddListener(close_btnClick);//关闭 21 } 22 23 // Update is called once per frame 24 void Update() 25 { 26 27 } 28 29 public void send_smg() 30 { 31 Send(inputText.text); 32 } 33 public void close_btnClick() 34 { 35 close(); 36 } 37 38 /// <summary> 39 /// 连接服务器 40 /// </summary> 41 static Socket socket_client; 42 public static void ConnectServer() 43 { 44 try 45 { 46 IPAddress pAddress = IPAddress.Parse("127.0.0.1"); 47 IPEndPoint pEndPoint = new IPEndPoint(pAddress, 52315); 48 socket_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 49 socket_client.Connect(pEndPoint); 50 Debug.Log("连接成功"); 51 //创建线程,执行读取服务器消息 52 Thread c_thread = new Thread(Received); 53 c_thread.IsBackground = true; 54 c_thread.Start(); 55 } 56 catch (System.Exception) 57 { 58 59 Debug.Log("IP端口号错误或者服务器未开启"); 60 } 61 } 62 63 /// <summary> 64 /// 读取服务器消息 65 /// </summary> 66 public static void Received() 67 { 68 while (true) 69 { 70 try 71 { 72 byte[] buffer = new byte[1024]; 73 int len = socket_client.Receive(buffer); 74 if (len == 0) break; 75 string str = Encoding.UTF8.GetString(buffer, 0, len); 76 Debug.Log("客户端打印服务器返回消息:" + socket_client.RemoteEndPoint + ":" + str); 77 } 78 catch (System.Exception) 79 { 80 81 throw; 82 } 83 84 } 85 } 86 /// <summary> 87 /// 发送消息 88 /// </summary> 89 /// <param name="msg"></param> 90 public static void Send(string msg) 91 { 92 try 93 { 94 byte[] buffer = new byte[1024]; 95 buffer = Encoding.UTF8.GetBytes(msg); 96 socket_client.Send(buffer); 97 } 98 catch (System.Exception) 99 { 100 101 Debug.Log("未连接"); 102 } 103 } 104 /// <summary> 105 /// 关闭连接 106 /// </summary> 107 public static void close() 108 { 109 try 110 { 111 socket_client.Close(); 112 Debug.Log("关闭客户端连接"); 113 SceneManager.LoadScene("control"); 114 } 115 catch (System.Exception) 116 { 117 Debug.Log("未连接"); 118 } 119 } 120 }
将服务器脚本和客户端脚本分别挂载在各自对应unity对象上即可实现socket tcp连接通讯。