简体   繁体   English

C#:TCPSocket读写最佳实践

[英]C#: TCPSocket read & write best practice

I have an issue with my C#/Unity code. 我的C#/ Unity代码有问题。 I tried to use while(true) but it's not working and has the infinite loop. 我尝试使用while(true)但是它不起作用并且具有无限循环。

Explain please what's the problem there? 请解释那里有什么问题? How could I do reading and writing to socket all the time while the socket is alive? 套接字处于活动状态时,如何一直对套接字进行读写?

Thank you. 谢谢。

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

Found the easy solution with System.Threading . 通过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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM