Unity中的简单套接字服务器

Unity中的简单套接字服务器,第1张

Unity中的简单套接字服务器

使用线程来做您的服务器侦听和读写 *** 作。您可以将套接字和其他networkstream对象声明为公共对象,然后在线程函数中对其进行初始化。

Unity无法很好地与Threads中的while循环配合使用,有时可能会 冻结 ,但您可以通过在要读取或等待数据从套接字到达的地方添加循环来
解决 此问题。

System.Threading.Thread.Sleep(1);``while

确保停止Thread in

onDisable()
功能。请 不要 在新的线程函数访问统一API。只需在此执行套接字 *** 作,然后将数据返回到
公共 变量即可。

System.Threading.Thread SocketThread;volatile bool keepReading = false;// Use this for initializationvoid Start(){    Application.runInBackground = true;    startServer();}void startServer(){    SocketThread = new System.Threading.Thread(networkCode);    SocketThread.IsBackground = true;    SocketThread.Start();}private string getIPAddress(){    IPHostEntry host;    string localIP = "";    host = Dns.GetHostEntry(Dns.GetHostName());    foreach (IPAddress ip in host.AddressList)    {        if (ip.AddressFamily == AddressFamily.InterNetwork)        { localIP = ip.ToString();        }    }    return localIP;}Socket listener;Socket handler;void networkCode(){    string data;    // Data buffer for incoming data.    byte[] bytes = new Byte[1024];    // host running the application.    Debug.Log("Ip " + getIPAddress().ToString());    IPAddress[] ipArray = Dns.GetHostAddresses(getIPAddress());    IPEndPoint localEndPoint = new IPEndPoint(ipArray[0], 1755);    // Create a TCP/IP socket.    listener = new Socket(ipArray[0].AddressFamily,        SocketType.Stream, ProtocolType.Tcp);    // Bind the socket to the local endpoint and     // listen for incoming connections.    try    {        listener.Bind(localEndPoint);        listener.Listen(10);        // Start listening for connections.        while (true)        { keepReading = true; // Program is suspended while waiting for an incoming connection. Debug.Log("Waiting for Connection");     //It works handler = listener.Accept(); Debug.Log("Client Connected");     //It doesn't work data = null; // An incoming connection needs to be processed. while (keepReading) {     bytes = new byte[1024];     int bytesRec = handler.Receive(bytes);     Debug.Log("Received from Server");     if (bytesRec <= 0)     {         keepReading = false;         handler.Disconnect(true);         break;     }     data += Encoding.ASCII.GetString(bytes, 0, bytesRec);     if (data.IndexOf("<EOF>") > -1)     {         break;     }     System.Threading.Thread.Sleep(1); } System.Threading.Thread.Sleep(1);        }    }    catch (Exception e)    {        Debug.Log(e.ToString());    }}void stopServer(){    keepReading = false;    //stop thread    if (SocketThread != null)    {        SocketThread.Abort();    }    if (handler != null && handler.Connected)    {        handler.Disconnect(false);        Debug.Log("Disconnected!");    }}void onDisable(){    stopServer();}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5559868.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存