我在互联网上找到这个代码并且不明白服务器如何为客户端发送完整大小以及客户端为什么知道文件大小。帮助我回复:(
Code server:
FileStream fs = null;
FileInfo fi = new FileInfo(textBox4.Text);
ulong fileSize = (ulong)fi.Length;
byte[] buf = new byte[32 * 1024];
MemoryStream ms = new MemoryStream(buf);//
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(fileSize);
fs = File.OpenRead(textBox4.Text);
int ns = socket.Send(buf, sizeof(ulong), SocketFlags.None);//why only 32KB which client
//can know file size
ulong pos = 0;
while (pos < fileSize)
{ int nr = fs.Read(buf, 0, buf.Length);
if (nr <= 0) { break; }
pos += (ulong)nr;
ns = socket.Send(buf, nr, SocketFlags.None);
}
代码客户端:
FileStream fs = null;
fs = File.Create(saveFileName);
byte[] buf = new byte[32 * 1024];
int nr = socket.Receive(buf, sizeof(ulong), SocketFlags.None);
MemoryStream ms = new MemoryStream(buf);
BinaryReader br = new BinaryReader(ms);
ulong fileSize = br.ReadUInt64();
ulong pos = 0;
while (pos < fileSize)
{ nr = socket.Receive(buf);
if (nr <= 0) { throw new Exception("Receive 0 byte"); }
pos += (ulong)nr;
fs.Write(buf, 0, nr);
}
答案 0 :(得分:1)
服务器首先写下这个:
bw.Write(fileSize);
客户首先阅读:
ulong fileSize = br.ReadUInt64();
Ergo,客户端知道要跟随多少字节。