阅读的NetworkStream不进流 [英] Reading NetworkStream doesn't advance stream
问题描述
我有其中服务器传送一个4字节整数,指定下一个传输是多大将是一个客户机 - 服务器应用程序。当我看到在客户端的4字节整数(指定FILE_SIZE),下一次我读的流,我得到FILE_SIZE + 4个字节读取。
我需要指定从此流读取时的偏移量为4,或者是有什么办法可以自动前进的NetworkStream,所以我的偏移可始终为0?
服务器
的NetworkStream theStream = theClient.getStream();
// ...
//计算文件大小的FileInfo和投入的byte []大小
// ...
theStream。写(大小,0,size.Length);
theStream.Flush();
客户端
的NetworkStream theStream = theClient.getStream();
//读取大小
字节[] =尺寸新的字节[4];
INT读取动作= theStream.Read(大小,0,4);
...
//读取内容
字节[] =内容新的字节[4096];
读取动作= theStream.Read(含量为0,4096);
Console.WriteLine(读取动作); //< - 打印文件大小+ 4
右键;找到了; FileInfo.Length
是长
;你要调用:
binWrite.Write(fileInfo.Length);
写8个字节,小尾数。然后你看的回通过:
文件大小= binRead.ReadInt32();
其中的小尾数会给你同一个值(32位, 至少)。你有4 00
字节闲置在流,虽然(从高字节长
) - 因此,4字节的不匹配
使用之一:
-
binWrite.Write((INT)fileInfo.Length);
-
文件大小= binRead.ReadInt64();
I have a client-server application where the server transmits a 4-byte integer specifying how large the next transmission is going to be. When I read the 4-byte integer on the client side (specifying FILE_SIZE), the next time I read the stream I get FILE_SIZE + 4 bytes read.
Do I need to specify the offset to 4 when reading from this stream, or is there a way to automatically advance the NetworkStream so my offset can always be 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
Right; found it; FileInfo.Length
is a long
; your call to:
binWrite.Write(fileInfo.Length);
writes 8 bytes, little-endian. You then read that back via:
filesize = binRead.ReadInt32();
which little-endian will give you the same value (for 32 bits, at least). You have 4 00
bytes left unused in the stream, though (from the high-bytes of the long
) - hence the 4 byte mismatch.
Use one of:
binWrite.Write((int)fileInfo.Length);
filesize = binRead.ReadInt64();
这篇关于阅读的NetworkStream不进流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!