Staffan Mattsson
Staffan Mattsson

Reputation: 31

NetworkStream.Read throws no exception

I cannot get this example to run: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx

The only thing Ive changed with their code is to put everything in the main method, and my port name of course. I Can connect to my server, and even send data. But on the line

Int32 bytes = networkStream.Read(data, 0, data.Length); 

The program stops running without an exception. How can microsoft own code not work? My server doesnt send anything yet, but I dont think that should matter? (It recieves perfectly though.) Ive Read something that you cannot se exceptions in other threads, but I dont have any. I also tried this thread: C# tcp socket (networkstream.read won't work with 8.1)

It doesnt work. I run win 7 thoguh. But I wish this to work an all new windows.

Upvotes: 0

Views: 2929

Answers (2)

Nemo
Nemo

Reputation: 3373

NetworkStream.Read() is a synchronous call, it will wait till a response is received. To read data of different lengths, you can do something like below.

NOTE: I'm assuming server is sending only one response for a request.

private string GetResponse(string command)
{
    //Send request
    TcpClient client = new TcpClient(HOST, PORT);
    Byte[] data = Encoding.ASCII.GetBytes(command);
    NetworkStream stream = client.GetStream();
    stream.Write(data, 0, data.Length);

    //Read response
    data = new Byte[BUFFER_SIZE];
    String response = String.Empty;
    stream.ReadTimeout = READ_TIMEOUT;
    while (!response.EndsWith(RESPONSE_END))
    {
        int bytes = stream.Read(data, 0, data.Length);
        response += Encoding.ASCII.GetString(data, 0, bytes);
    }
    response = response.Remove(response.Length - RESPONSE_END.Length);
    stream.Close();
    client.Close();

    //Return
    return response;
}

Upvotes: 0

C.Evenhuis
C.Evenhuis

Reputation: 26446

NetworkStream.Read blocks until data is available, the connection is closed (it will return 0 in that case) or an exception occurs. It is designed that way.

If your server would send data, your client program would continue and be able to process the response.

Upvotes: 3

Related Questions