unity Socket服务端
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Net; //IPAddress,IPEndPoint using System.Net.Sockets; //建立套接字socket using System.Threading; //建立线程thread using System.Text; using System.IO; using System.Xml; public class ServerSocketHandlers : MonoBehaviour { // Start is called before the first frame update void Start() { openServer(); } // Update is called once per frame void Update() { Send(); } public void openServer() { try { IPAddress pAddress = IPAddress.Parse("127.0.0.1"); //IP IPEndPoint pEndPoint = new IPEndPoint(pAddress, 3001); //端口号 Socket socket_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket_server.Bind(pEndPoint); socket_server.Listen(5);//设置最大连接数 Debug.Log("监听成功"); //创建新线程执行监听,否则会阻塞UI,导致unity无响应 Thread thread = new Thread(listen); thread.IsBackground = true; thread.Start(socket_server); } catch (System.Exception) { throw; } } Socket socketSend; public void Send() //要写成public,button的onclick才能捕捉到 { string danmustr = "{ \"type\": \"danmu\", \"UID\": 16125790, \"uname\": \"咕之助\", \"msg\": \""; byte[] buffer = Encoding.UTF8.GetBytes(danmustr); socketSend.Send(buffer); } void listen(object o) //不管接受还是发送都要先监听 { try { Socket socketWatch = o as Socket; while (true) { socketSend = socketWatch.Accept(); Debug.Log(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功"); Thread r_thread = new Thread(Received); //可以不要这个接受,只负责发送(发送可以写在update里) r_thread.IsBackground = true; r_thread.Start(socketSend); } } catch (System.Exception) { throw; } } void Received(object o) { try { Socket socketSend = o as Socket; while (true) { byte[] buffer = new byte[1024]; int len = socketSend.Receive(buffer); if (len == 0) break; string str = Encoding.UTF8.GetString(buffer, 0, len); Debug.Log("服务器打印客户端返回消息:" + socketSend.RemoteEndPoint + ":" + str); Send(); //也可以跟在接受的消息后再发送 } } catch (System.Exception) { throw; } } }