Unity中的简单套接字服务器

我想在Unity项目中使用C#插件。该插件应充当服务器,它将从客户端获取值,以便我可以将这些值用于进一步处理。问题是服务器具有无限循环。无限循环会导致Unity挂起。如何处理呢?


编辑:我附上服务器程序的代码段。我认为有2点可能会引起问题。如代码中所述,无限循环和暂停程序的地方:


void networkCode()

{

    // Data buffer for incoming data.

    byte[] bytes = new Byte[1024];


    // Establish the local endpoint for the socket.

    // Dns.GetHostName returns the name of the 

    // host running the application.

    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());

    IPAddress ipAddress = ipHostInfo.AddressList[0];

    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 1755);


    // Create a TCP/IP socket.

    listener = new Socket(ipAddress.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)

        {

            // Program is suspended while waiting for an incoming connection.

            Debug.Log("HELLO");     //It works

            handler = listener.Accept();

            Debug.Log("HELLO");     //It doesn't work

            data = null;


            // An incoming connection needs to be processed.

            while (true)

            {

                bytes = new byte[1024];

                int bytesRec = handler.Receive(bytes);

                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());

    }

}


吃鸡游戏
浏览 379回答 3
3回答

猛跑小猪

C#插件已完成。但是Unity没有读取正确的值。我附加了Unity边码:using UnityEngine;using System;using SyncServerDLL;&nbsp; &nbsp; //That's our librarypublic class receiver : MonoBehaviour {&nbsp; &nbsp; SynchronousSocketListener obj;&nbsp; &nbsp;//That's object to call server methods&nbsp; &nbsp; // Use this for initialization&nbsp; &nbsp; void Start() {&nbsp; &nbsp; &nbsp; &nbsp; obj = new SynchronousSocketListener ();&nbsp; &nbsp; &nbsp; &nbsp; obj.startServer ();&nbsp; &nbsp; }&nbsp; &nbsp; // Update is called once per frame&nbsp; &nbsp; void Update() {&nbsp; &nbsp; &nbsp; &nbsp; Debug.Log (obj.data);&nbsp; &nbsp; }}我已经在Visual Studio中彻底测试了SynchronousSocketListener类。在那里效果很好。

MM们

您不调用networkCode或Start()方法。您调用该&nbsp;startServer();方法。Start()游戏开始时,Unity会自动调用该方法。您可以startServer();通过从调用我已经做过的&nbsp;代码Start()。请查看我上面发布的代码,如果您不知道如何Start()调用以及何时调用,我建议学习Unity API&nbsp;。
打开App,查看更多内容
随时随地看视频慕课网APP