TcpClient - An existing connection was forcibly closed by the remote host

后端 未结 3 1196
一生所求
一生所求 2021-01-05 19:06

The Info

I have been developing a web http server in c# and decided to add a remote console feature. The console can be used from any location and u

3条回答
  •  星月不相逢
    2021-01-05 19:37

    I had same solution. it is usually happens if client is disconnected. Solution from Alex RG is not working unfortunately. you will get another exception. Best solutions is described here by Microsoft

    you need to check using CanRead

    TcpClient tcpClient = new TcpClient ();
    
    // Uses the GetStream public method to return the NetworkStream.
    NetworkStream netStream = tcpClient.GetStream ();
    
    if (netStream.CanRead)
    {
        // Reads NetworkStream into a byte buffer.
        byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
    
        // Read can return anything from 0 to numBytesToRead. 
        // This method blocks until at least one byte is read.
        netStream.Read (bytes, 0, (int)tcpClient.ReceiveBufferSize);
    
        // Returns the data received from the host to the console.
        string returndata = Encoding.UTF8.GetString (bytes);
    
        Console.WriteLine ("This is what the host returned to you: " + returndata);
    
    }
    else
    {
        Console.WriteLine ("You cannot read data from this stream.");
        tcpClient.Close ();
    
        // Closing the tcpClient instance does not close the network stream.
        netStream.Close ();
        return;
    }
    

提交回复
热议问题