What is the correct way to read from NetworkStream in .NET

前端 未结 3 1866
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 04:06

I\'ve been struggling with this and can\'t find a reason why my code is failing to properly read from a TCP server I\'ve also written. I\'m using the TcpClient

3条回答
  •  暖寄归人
    2020-11-27 04:37

    As per your requirement, Thread.Sleep is perfectly fine to use because you are not sure when the data will be available so you might need to wait for the data to become available. I have slightly changed the logic of your function this might help you little further.

    string SendCmd(string cmd, string ip, int port)
    {
        var client = new TcpClient(ip, port);
        var data = Encoding.GetEncoding(1252).GetBytes(cmd);
        var stm = client.GetStream();
        stm.Write(data, 0, data.Length);
        byte[] resp = new byte[2048];
        var memStream = new MemoryStream();
    
        int bytes = 0;
    
        do
        {
            bytes = 0;
            while (!stm.DataAvailable)
                Thread.Sleep(20); // some delay
            bytes = stm.Read(resp, 0, resp.Length);
            memStream.Write(resp, 0, bytes);
        } 
        while (bytes > 0);
    
        return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
    }
    

    Hope this helps!

提交回复
热议问题