【发布时间】:2012-02-24 21:17:46
【问题描述】:
我正在尝试学习网络基础知识,并且我已经根据this 教程构建了一个回显服务器。我用 telnet 检查了服务器,它运行良好。
现在,当我使用 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();
效果不是很好。如果我要评论 stream.Read 行,一切正常(希望我看不懂)。我也试图以类似的方式使用异步回调方法进行读取。然后它只在我终止程序后才起作用(服务器处理请求)
我怀疑我从流中读取的方式导致了这个块,但我太无能了,无法理解我做错了什么。
【问题讨论】:
-
您确定服务器正在向您发送您可以阅读的内容吗?
-
我无法通过调试来判断,但我看到了在 telnet 中打印回来的数据。我什至在服务器响应的末尾添加了“X”,以确保它是来自服务器的回复。
-
回显服务器如何读取消息?您是否看到回显服务器何时收到消息并回复您上面的代码?
-
您忘记了 client.Connect() 调用。
-
也许回显服务器在发送回消息之前等待换行符
\n?
标签: c# sockets networkstream