我正在尝试学习网络的基础知识,并且我已经从this教程构建了一个echo服务器。我用telnet检查了服务器,它运行正常。
现在,当我在互联网上使用一些客户端样本时:
// 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();
效果不佳。如果我将评论stream.Read行,一切都很完美(期望我无法阅读)。我也试图以类似的方式使用异步回调方法来完成读取。然后它只在我终止程序(服务器处理请求)后才能工作
我怀疑我从流中读取的方式导致了这个阻塞,但是我太无能为力了解我做错了什么。
答案 0 :(得分:1)
实现将阻塞,直到至少一个字节的数据可以 如果没有可用的数据,请阅读。
来自MSDN
您的服务器可能没有向您发送任何数据。
修改强>
我测试了你的客户端,它运行得很好。亲自尝试并设置以下参数:
string server = "google.com";
int port = 80;
string message = "GET /\n";
这绝对是你的服务器有问题。