简体   繁体   中英

What happens when we do networkstream.write()?

I have 2 programs. 1 server and 1 client.

In the client it goes something like this:

while(statement)
{
    networkstream.write(data);
}

And in the server it goes something like this:

while(statement)
{
    while(statement)
    {
        ReceiveData;
    }

    Do other stuff;
}

So, while the client can write to the network stream really fast, the server still has to attend to the data before he can read some more.

What happens when the client has already made 4 laps of the loop containing the write, while the server has still only read 1 time for example.

Is there a way of letting the client know when he can make another write? And also what happens when the client make several '.write'? does the server keep them all and reads them all or does the data that has been sent get overwriten?

Hopefully you can understand my question. Edit the question title if you desire.

There is a whole stack of layers between your .write and the actual wires. The layers do all kinds of stuff, from error correction to making sure that your network traffics does not collide with others etc.; non the least, they provide you with buffering and blocking (if you sent too much or - on the receiving side - there is no data yet).

To answer your question, somewhere along the line will be a buffer (a chunk of memory) where your bytes are written to. Until they are sent along to the next stop along the way, it will block (wait/hang...). These calls will travel down the stack, up on the receiving side, and then down the other side and up yours again. So when your write returns, you can be reasonably sure that all is well, unless you get back an error code, exception or however your error handling works.

If the server is slow when processing your requests, it will not get to read as quick as you'd like, so the buffers between you and them will fill up, at which point writing stops.

There are plenty of different buffers on different layers as well, a full answer would be pretty complex. https://en.wikipedia.org/wiki/OSI_model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM