我有一个客户端-服务器应用程序,其中服务器传输一个 4 字节整数,指定下一次传输的大小。当我在客户端读取 4 字节整数(指定 FILE_SIZE)时,下次读取流时,我会读取 FILE_SIZE + 4 个字节。
从此流读取时是否需要将偏移量指定为 4,或者是否有办法自动推进 NetworkStream,以便我的偏移量始终为 0?
SERVER
NetworkStream theStream = theClient.getStream();
//...
//Calculate file size with FileInfo and put into byte[] size
//...
theStream.Write(size, 0, size.Length);
theStream.Flush();
CLIENT
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
正确的;找到了;FileInfo.Length
is a long
;您致电:
binWrite.Write(fileInfo.Length);
写入8个字节,小尾数法。然后你可以通过以下方式读回:
filesize = binRead.ReadInt32();
which 小尾数法会给你相同的值(至少对于 32 位)。你有 4 个00
不过,流中未使用的字节(从long
) - 因此 4 字节不匹配。
使用以下之一:
binWrite.Write((int)fileInfo.Length);
filesize = binRead.ReadInt64();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)