【发布时间】:2016-07-31 07:05:01
【问题描述】:
我想在我的 Unity 项目中使用 C# 插件。该插件应该充当从客户端获取值的服务器,以便我能够使用这些值进行进一步处理。 问题是服务器有无限循环。无限循环会导致 Unity 挂起。如何处理?
编辑:我附上了服务器程序的代码 sn-p。在我看来,有两点可能会导致问题。代码中注释的无限循环和程序暂停点:
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());
}
}
编辑:在@Programmer 的帮助下,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 类。它在那里取得了很好的效果。
【问题讨论】:
-
用你挂起的代码更新你的问题
-
@Programmer:他提供了解释“挂起”的相关信息:代码是一个无限等待循环,就像您通常在(幼稚的)套接字服务器中编写的那样。问题是他在插件中执行此操作,他在主统一线程中运行。这有效地“挂起”了 Unity。也就是说,一些代码会很好。
-
@Paul-Jan 添加了一些代码来给出一个粗略的想法。
-
@Paul-Jan。我知道他遇到的问题。我想通过修复他的代码来提供解决方案,而不是花时间从头开始编写新代码。还想确保他有一些东西并且不希望人们编写他所有的代码。
-
@Programmer 如果需要,我可以添加更多代码。我可以为自己做编码部分。我只需要一个方向。