Reputation: 40
I find this code on internet and dont understand how server can send full size for client and why client can know file size. Help me response :(
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);
}
Code client:
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);
}
Upvotes: 0
Views: 101
Reputation: 38810
The server first writes this:
bw.Write(fileSize);
The client first reads this:
ulong fileSize = br.ReadUInt64();
Ergo, the client knows how many bytes are to follow.
Upvotes: 1