Search code examples
c#tcpclient

TCPClient Error: "System.InvalidOperationExceptio"


I've been creating a TCPClient which is suppose to connect to a server but am getting this error:

System.InvalidOperationException: 'The operation is not allowed on non-connected sockets.'

Here's my Code:

Public String IPAddress = "192.168.100.xxx"
Public Int32 Port = 23;
public TcpClient client = new TcpClient();

public void Connect() {
    client.Connect(IPAddress, Port);
    // send first message request to server
    Byte[] msg_data = System.Text.Encoding.ASCII.GetBytes("Hello Server);

    // uses the GetStream public method to return the NetworkStream
    NetworkStream netStream = _client.GetStream();

    // write message to the network
    netStream.Write(msg_data, 0, msg_data.Length);

    // buffer to store the response bytes
    msg_data = new Byte[256];

    // read the first batch of response byte from arduino server
    Int32 bytes = netStream.Read(msg_data, 0, msg_data.Length);
    received_msg = System.Text.Encoding.ASCII.GetString(msg_data, 0, bytes);

    netStream.Close();

}

public void Send() {
    // message data byes to be sent to server
    Byte[] msg_data = System.Text.Encoding.ASCII.GetBytes(_sendMessage);

    // uses the GetStream public method to return the NetworkStream

    // ** Error Here: System.InvalidOperationException: 'The operation is not allowed on non-connected sockets.'
    NetworkStream netStream = client.GetStream(); 

    // write message to the network
    netStream.Write(msg_data, 0, msg_data.Length);

    // buffer to store the response bytes
    msg_data = new Byte[256];

    // read the first batch of response byte from arduino server
    Int32 bytes = netStream.Read(msg_data, 0, msg_data.Length);
    received_msg = System.Text.Encoding.ASCII.GetString(msg_data, 0, bytes);

    netStream.Close(); // close Stream
}

I am getting and error when creating a new instance of NetworkStream netStream = client.GetStream();. Been struggling to find whats causing the error, I think it's somehow closing the connection above.

Everything is in a class and must be called at anyplace in the software.


Solution

  • client.GetStream() is implemented like:

    return new NetworkStream(this.Client, true);
    

    whereas the true means if the stream is disposed/closed it also closes/disconnects the socket/client. You should be able to avoid this by directly calling

    var netStream = new NetworkStream(client.Client, false);
    

    And even better would be instead of:

    NetworkStream netStream = client.GetStream();
    …
    netSteam.Dlose();
    

    to ensure that the stream is always closed even if an errors by writing:

    using (var netStream = new NetworkStream(client.Client, false))
    {
      …
    }