我有一个用作套接字服务器的 Unity 应用程序:
public class Server : MonoBehaviour
{
private String outData;
private String inData;
public void writeData(String data){
outData = data;
}
void Start()
{
ThreadStart ts = new ThreadStart(dataHandler);
mThread = new Thread(ts);
mThread.Start();
}
void dataHandler()
{
TcpListener listener = new TcpListener(PORT);
listener.Start();
while (true)
{
var client = listener.AcceptTcpClient();
new Thread(() =>
{
using (client)
{
var reader = new StreamReader(client.GetStream());
var writer = new StreamWriter(client.GetStream());
while (true)
{
inData = reader.ReadLine();
if(outData != null){
writer.WriteLine(outData);
writer.Flush();
outData = null;
}
}
}
}).Start();
}
}
}
我不熟悉 .NET 线程,不知道如何发送数据。当数据到来时,socket 线程被唤醒并且 inData 字段更新。但是当我调用 writeData 时,什么也没有发生。套接字线程继续休眠,直到 inData 更新。