如何等待直到流写入完成

本文关键字:何等待 等待 | 更新日期: 2023-09-27 18:07:04

我有一个服务器应用程序,监听端口8888上的连接。我还创建了客户机应用程序。这是一个简单的应用程序,唯一困难的是管理多个连接。所以我只需要在电脑之间发送文件,我不知道这样做是否正确,但是它可以工作,也许你们可以纠正我。以下是我发送文件时的算法:

NetworkStream stream = '' initialize it
while(someCondition)
{
  // first I open the file for reading and read chunks of it
  byte[] chunk = fileRead(file, indexStart, indexEnd) // I have a similar method this is just to illustate my point
  stream.Write(chunk, ''other params)
   // since I often send large files it will be nice if I can wait here 
   // until the stream.Write is done. when debuging this the while loop 
   // executes several times then it waits. 
}

,另一边从流中读取字节并将其写入文件。

我有时也需要等待,因为我发送多个文件,我想确保在移动到下一个文件之前发送了第一个文件。我知道我可以用流来解它。一旦传输完成,Read方法。并从客户端发回数据。但有时我相信它会帮助知道什么时候流。


编辑

ok,所以根据你的答案,我可以发送给客户端,例如我打算发送的字节数。一旦客户端接收到这么多字节,就意味着完成了。但我的问题是,这是否有效。我的意思是像

在服务器上:

写入数据"发送文件长度"

读取数据"检查客户端是否收到长度"(例如期望字符串ok)

write data "告诉客户端文件名"

read data "查看客户端是否收到文件名"

write data "start send chunk of file"

读取数据"等待,直到客户端回复字符串ok,例如"

如何等待直到流写入完成

stream.Write(chunk, ''other params)

完成。值得注意的是,这并不意味着另一端收到了任何东西。实际上,在该行之后,数据很可能在发送机器上的某个缓冲区中。这就意味着你已经无法控制了。如果您需要收据确认,远端必须让您知道。

流。写操作是同步的,所以它会一直阻塞线程,直到写操作完成。