Read bytes from NetworkStream (Hangs)

十年热恋 提交于 2019-11-28 11:28:56

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/9431067/read-bytes-from-networkstream-hangs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!