C#:TCPSocket read&写出最佳实践

时间:2017-09-15 00:13:14

标签: c# sockets tcp

我的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);
}

1 个答案:

答案 0 :(得分:0)

使用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);
    }
}