jkh*_*jkh 3 c# networkstream stream
我有一个客户端 - 服务器应用程序,其中服务器传输一个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();
Run Code Online (Sandbox Code Playgroud)
客户
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
Run Code Online (Sandbox Code Playgroud)
对; 找到了; FileInfo.Length是一个long; 你的电话:
binWrite.Write(fileInfo.Length);
Run Code Online (Sandbox Code Playgroud)
写8个字节,little-endian.然后你通过以下方式阅读:
filesize = binRead.ReadInt32();
Run Code Online (Sandbox Code Playgroud)
哪个little-endian会给你相同的值(至少32位).00但是,在流中没有使用4 个字节(从高字节开始long) - 因此4字节不匹配.
使用以下之一:
binWrite.Write((int)fileInfo.Length);filesize = binRead.ReadInt64();