【发布时间】:2011-10-27 04:48:17
【问题描述】:
我有一个客户端-服务器应用程序,其中服务器传输一个 4 字节整数,指定下一次传输的大小。当我在客户端读取 4 字节整数(指定 FILE_SIZE)时,下一次读取流时,我会读取 FILE_SIZE + 4 字节。
从该流中读取时是否需要将偏移量指定为 4,或者是否有办法自动推进 NetworkStream 以便我的偏移量始终为 0?
服务器
NetworkStream theStream = theClient.getStream();
//...
//Calculate file size with FileInfo and put into byte[] size
//...
theStream.Write(size, 0, size.Length);
theStream.Flush();
客户
NetworkStream theStream = theClient.getStream();
//read size
byte[] size = new byte[4];
int bytesRead = theStream.Read(size, 0, 4);
...
//read content
byte[] content = new byte[4096];
bytesRead = theStream.Read(content, 0, 4096);
Console.WriteLine(bytesRead); // <-- Prints filesize + 4
【问题讨论】:
-
什么是
filesize?和size.Length一样吗? -
你确定
size.Length(服务器端)是4吗? (而且您在客户端第二次读取时没有读取下一个文件的大小?) -
什么是大小?你所做的将是不稳定的。使用 BinaryReader/BinaryWriter 代替 ReadInt32/WriteInt32 以避免大小问题。
-
NetworkStream不支持随机访问网络数据流。 CanSeek 属性的值,表示流是否支持查找,始终为 false;读取 Position 属性、读取 Length 属性或调用 Seek 方法将引发 NotSupportedException。 - 来自MSDN。也许您可以在读取内容时读取流并丢弃前 4 个字节? -
size 是通过 BitConverter.GetBytes(fileInfo.Length) 获得的字节[];其中 fileInfo = new FileInfo(myFileName);
标签: c# stream networkstream