0
我在網上找到這段代碼,並不明白服務器如何發送客戶端的全部大小以及爲什麼客戶端可以知道文件大小。幫我回應:(關於操作memoryStream
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);
}
謝謝:)。 buf發送幾次或只發送一次@ Moo-Juice –
@ThanhBình不確定你的意思 - 在上面粘貼的示例代碼中,服務器發送文件的大小,然後發送整個文件本身。客戶端讀取長度,然後讀取,直到它讀取了足夠的字節(或出現錯誤並拋出異常)。 –
int ns = socket.Send(buf,sizeof(ulong),SocketFlags.None);我想知道大小buf超過32kb這行代碼和套接字發送多次客戶端知道大小的文件?對不起,我的英語不好:) –