【发布时间】:2020-01-06 15:16:12
【问题描述】:
更新
我发现了问题所在。我试图通过 TCP 移动太多数据,这导致了冻结。出于某种原因,这并没有体现在编辑器中……谁知道是什么原因。如果其他人偶然发现了这个问题(在像 Unity 这样的程序中,函数不断循环并且数据总是被处理),请考虑您正在移动太多不相关的数据。
原帖
我遇到了相当大的问题,希望能得到一些指导。
简而言之,我想知道如何使用 TCP 在同一台计算机上通信两个 Unity 应用程序。我已经让它在编辑器中运行了,但是当这两个应用程序都被构建时,通信很快就会中断。
这真的难倒我,因为我不明白为什么应用程序可以在编辑器环境中运行,但不能在正式版本中运行。
当我使用 TCP 在两个 Unity 应用程序(在同一台计算机上)之间进行通信时,只要其中一个应用程序保留在 Unity 环境中,它就可以工作。也就是说,如果我构建一个应用程序,然后在 Unity 编辑器中打开另一个应用程序,TCP 通信就可以完美运行。
这里有更多背景信息:我的一个应用程序用作用户界面,另一个应用程序与窥镜接口以提供游戏内对象的全息显示。最初,它们被合并到一个应用程序中——但我在让 Unity 的多显示器支持在不同分辨率的两台显示器之间运行时遇到了很多麻烦。 Look Glass factory 甚至提供了一个预制件来做到这一点,但它在当前的 SDK 中被破坏了。所以我求助于使用套接字来连接两个应用程序,每个监视器一个。
我正在使用 C# 的 TCP 侦听器类:https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcplistener?view=netframework-4.8
和 TCP 客户端类:https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=netframework-4.8
目前,UI 充当 TCPListener,生成全息图的应用程序是 TCPClient。在每个应用程序中,我使用了两个队列——一个传入消息队列和一个传出消息队列——它们是在主线程和网络线程之间共享的全局变量。
TCP 监听器:
private void Start()
{
incomingMessages = new Queue();
outgoingMessages = new Queue();
Application.runInBackground = true;
thread = new Thread(new ThreadStart(Receive));
thread.Start();
//stuff happens that's irrelevant to this question. And then...
}
void Receive()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
Debug.Log("About to reenter main while in Server...");
while (threadContinue)
{
Debug.Log("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Debug.Log("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Debug.Log("Received from Client: " + data);
lock (this)
incomingMessages.Enqueue(data);
string response = supplyData();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Debug.Log("Sent to Client: " + response);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Debug.Log("SocketException: ");
Debug.Log(e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Debug.Log("Exiting 'Receive'");
}
这里是 TCP 客户端。它会尝试定期连接,并且每当有新数据可用时也会尝试连接。这样它就可以定期从服务器接收信息并在可用时共享新数据:
void Start()
{
//prepare networking
Application.runInBackground = true;
outgoingMessages = new Queue();
incomingMessages = new Queue();
thread = new Thread(new ThreadStart(Connect));
thread.Start();
//stuff happens that's irrelevant to this question...
}
private void Connect()
{
String server = "127.0.0.1";
Int32 port = 13000;
string message = "";
while (threadContinue == true)
{
if (timeToConnect())
{
lastConnection = ourTime;
if (outgoingMessages.Count > 0)
message = outgoingMessages.Dequeue().ToString();
else
message = "Nothing to report.";
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Debug.Log("Sent to Server: " + message);
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
lock (this)
incomingMessages.Enqueue(responseData);
Debug.Log("Received from Server: " + responseData);
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Debug.Log("ArgumentNullException: ");
Debug.Log(e);
outgoingMessages.Enqueue(message);
}
catch (SocketException e)
{
Debug.Log("SocketException: ");
Debug.Log(e);
outgoingMessages.Enqueue(message);
}
}
}
}
private bool timeToConnect()
{
if ((ourTime - lastConnection > NETWORK_DELAY) || (outgoingMessages.Count > 0))
return true;
return false;
}
在单独的线程中实例化,以便 Unity 的主线程可以不受阻碍地继续。
再次 - 它可以在编辑器中使用,但是当我构建它时,它会损坏。
【问题讨论】:
-
您是否遇到特定错误?也许是关于端口不可用的问题?
-
能否请您添加您的实现代码
-
需要您的代码。需要你的错误。需要细节。端口是如何分配的?程序的两个实例是否在 prod 中竞争同一个端口?
-
我会添加一些代码,稍等。它正在使用队列。编辑器中没有错误 - 只有当我构建应用程序时它们才开始出现问题。这是一个重要的细节,只是为了确保没有人错过它。当一个应用程序仍在编辑器中时,TCP 工作正常。
-
@chapter12 问题寻求调试帮助(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及最短的在问题本身中重现它所必需的代码。请参阅:How to create a Minimal, Reproducible Example。
标签: c# unity3d tcp networkstream