我希望在我的Unity项目中使用一个C#插件。该插件应该作为服务器,从客户端获取值,以便我可以将这些值用于进一步处理。
问题是服务器有无限循环。无限循环会导致Unity挂起。如何处理?
编辑:我附上了服务器程序的代码片段。在我看来,可能会导致问题的有两个点。无限循环和程序被暂停的时候,如代码中所注释的那样。
编辑:我附上了服务器程序的代码片段。在我看来,可能会导致问题的有两个点。无限循环和程序被暂停的时候,如代码中所注释的那样。
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());
}
}
更新:在@程序员的帮助下,C#插件已经完成。但Unity没有读取正确的值。我附上了Unity端的代码:
using UnityEngine;
using System;
using SyncServerDLL; //That's our library
public class receiver : MonoBehaviour {
SynchronousSocketListener obj; //That's object to call server methods
// Use this for initialization
void Start() {
obj = new SynchronousSocketListener ();
obj.startServer ();
}
// Update is called once per frame
void Update() {
Debug.Log (obj.data);
}
}
我在Visual Studio中彻底测试了SynchronousSocketListener类,结果很好。