开发者

How to wait until stream write is done

I have a server app that listens for connections on port 8888. I am also creating the client application. It is a simple application the only hard thing about it is managing multiple connections. so I just need to send files between computers so the way I do that, I don't know if it is wright but it works maybe you guys can correct me. here is my algorithm when sending the file:

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. 

}

and on the other side I read bytes from that stream and write it to a file.

I also need to wait sometimes because I send multiple files and I want to make sure开发者_运维知识库 that the first file has been sent before moving to the next. I know I can solve this by using the stream.Read method once the transfer has been done. and sending data back from the client. but sometimes I believe it will be helpful to know when the stream.write is done.


Edit

ok so based on your answers I can for example send to the client the number of bytes that I am planing to send. and once the client recives that many bytes it means it is done. But my question is if this is efficient. I mean doing something like

on the server:

writing data "sending the file length"

read data "check to see if the client received the length" (expecting a string ok for example)

write data "tel the client the name of the file"

read data "check to see if the client recived the name of the file"

write data "start sending chuncks of the file"

read data "wait until client replies with the string ok for example"


The write is complete when the line

stream.Write(chunk, \\other params)

completes. It's worth noting that this does not imply that the other end has received anything. In fact, immediately subsequent to that line, the data is likely to be in some buffer on the sending machine. That means that it's now out of your control. If you want receipt confirmation, the remote end will have to let you know.


Stream.Write is synchronous, so it will always block your thread until the writing finishes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜