A
A
Alexey Polyakov2019-01-27 10:04:23
PHP
Alexey Polyakov, 2019-01-27 10:04:23

How does a network socket work when writing/reading?

Good afternoon,
Explain in simple terms how the socket-stream connection works when reading a record? In particular, we create a socket, create a stream, write data from the buffer there, at the other end while waiting for data while (true), then, usually in examples, we send and wait for a response, in php for example $ out = socket_read, etc. , and if there is no data or it is delayed, or first the first part was sent there, and the second part was sent after five seconds, and here socket_read == false. How is it all regulated in order to move away from the scheme sent-immediately received, closed and forgotten? How to manage who is waiting, how long is waiting, what is waiting, etc.?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Yudakov, 2019-01-27
@Stilist

A TCP socket is a transport layer, its task is: to transfer a sequence of bytes from the sender to the recipient, while:
a) not losing bytes;
b) deliver those bytes in exactly the order in which they were sent.
This completes the socket tasks. Those. your question is not related to sockets.
The question of how much to read (and wait) is decided not at the transport, but at the application level. Those. in fact, you are faced with the task: to develop an application layer protocol - to come up with rules for what and how much each side of the network interaction should send and wait.
One easy way to solve this problem is to have each side specify the length of that data (eg 4 bytes) before sending any data.
Then the work of the recipient in this case is simple:
1) read from the socket 4 bytes - the length of the message;
2) read from the socket as many more bytes as indicated in the message length.
And you should not pay attention to all sorts of DataAvailable, they only mislead. If the number of bytes we need has not yet arrived, we are waiting for it to arrive.
Upd.
NetworkStream.DataAvailable only shows us that the data has already arrived and can be retrieved using Read, but does not say anything about how much more data is expected, and even more so does NOT signal that the other side has completed the data transfer:
"Use the DataAvailable property to determine if data is ready to be read.
https://docs.microsoft.com/en-us/dotnet/api/system...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question