简体   繁体   中英

Read bytes from NetworkStream (Hangs)

I'm trying to learn the basics of networking and I've built an echo server from this tutorial. I checked the server with telnet and it works perfect.

Now when I'm using some of the many client samples on the Internet:

// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer 
// connected to the same address as specified by the server, port
// combination.
TcpClient client = new TcpClient(server, port);

// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

// Get a client stream for reading and writing.
NetworkStream stream = client.GetStream();

// Send the message to the connected TcpServer. 
stream.Write(data, 0, data.Length);

Console.WriteLine("Sent: {0}", message);

// Receive the TcpServer.response.

// Buffer to store the response bytes.
data = new Byte[256];

// String to store the response ASCII representation.
String responseData = String.Empty;

// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);

// Close everything.
stream.Close();
client.Close();

It doesn't work very well. If I will comment the stream.Read line, everything works perfect (expect I can't read). I was also trying to accomplish that in a similar way using asynchronous callback method for the read. and then it only works after I terminate the program (the server handles the request)

I suspect that the way I'm reading from the stream cause this block, but I'm too clueless to understand what I'm doing wrong.

The implementation will block until at least one byte of data can be read, in the event that no data is available.

From MSDN

Your server propably isn't sending you any data.

Edit:

I tested your client and it works perfectly fine. Try it yourself and set the following parameters:

  string server = "google.com";
  int port = 80;
  string message = "GET /\n";

It's definitely your server which has the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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