【发布时间】:2014-05-28 21:00:59
【问题描述】:
我试图用简单的 tcp 服务器接收 xml 文件。但我所有的努力都以从 NetworkStream 读取字节的应用程序结束。我不知道,有什么问题。
我已经尝试将源代码从答案复制到非常similar question。它看起来应该可以工作,但它没有
我的客户端发送xml的代码示例:
private void SendFile()
{
// stm is a class attribue NetworkStream defined in another method
byte[] dataToSend = File.ReadAllBytes(string_path_to_file);
stm.Write(dataToSend, 0, dataToSend.Length);
sstm.Flush();
}
我的服务器接收 xml 的代码示例:
public void RecieveFile()
{
Stream fs = new FileStream(path_to_recieved_file, FileMode.Create, FileAccess.ReadWrite);
Byte[] bytes = new Byte[1024];
int length;
//client was defined earlier, on establishing connection
NetworkStream networkStream = client.GetStream();
length = networkStream.Read(bytes, 0, bytes.Length);
while ((length = networkStream.Read(bytes, 0, bytes.Length)) != 0)
{
fs.Write(bytes, 0, length);
}
}
客户端工作正常。我正在发送测试 xml 文件(~533b),服务器可以读取这些数据。当我调试我的应用程序时,我可以看到第一次服务器将读取 533b(显然,整个文件)。然后写入它并在尝试第二次读取后停止响应。我希望在第二次阅读之后,当 networkStream 中没有任何内容时,我会得到 length=0 并且循环将停止。我做错了什么?
我非常感谢任何帮助。提前致谢。
【问题讨论】: