我的C#/Unity代码有问题。我试着使用while(true),但它不工作并且有无限循环。
请解释一下,有什么问题吗?当套接字处于活动状态时,我如何一直对套接字进行读写操作?
谢谢。
Socket clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect("127.0.0.1", 1442);
byte[] message = System.Text.Encoding.ASCII.GetBytes(JsonUtility.ToJson(new Message()));
clientSocket.Send(message);
while(true) {
byte[] data = new byte[1024];
int receivedDataLength = clientSocket.Receive(data);
string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
Debug.Log(stringData);
}发布于 2017-09-15 10:16:16
找到了使用System.Threading的简单解决方案。
void Start()
{
clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect("127.0.0.1", 1442);
byte[] message = System.Text.Encoding.ASCII.GetBytes(JsonUtility.ToJson(new GameMessage("ship/spawn", "")));
clientSocket.Send(message);
Thread polling = new Thread(HandleResponse);
polling.Start();
}
void HandleResponse()
{
while (true)
{
byte[] data = new byte[8056];
int receivedDataLength = clientSocket.Receive(data);
string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
Debug.Log(stringData);
}
}https://stackoverflow.com/questions/46229875
复制相似问题