Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the reading from and writing to sockets are synchronized?

Tags:

java

sockets

We create a socket. On one side of the socket we have a "server" and on another side there is a "client". Both, the server and client, can write to and read from the socket. It is what i understand. I do not understand the following things:

  1. If a server reads from the socket, does it see in the socket only those stuff which was written to the socket by the client? I mean if server writes something to the socket and than reads from the socket, will it (server) see in the socket the stuff it (server) wrote there? I hope not.

  2. Let's consider the following situation. A client write something to the socket and then it writes something new to the socket and then server reads from the socket. What will the server see there? Only the "new" stuff written by the client or both "new" and "old" one?

  3. If a client (or server) writes to the socket, can it see if the written information was received by other side? For example out.println("Hello, Server!") will return true it server received this message.

like image 559
Roman Avatar asked Oct 14 '22 08:10

Roman


1 Answers

A socket connection represents two unidirectional streams: one from the client to the server and one from the server to the client.

Each side can put data into one stream and read from the other.

Data put into one stream is appended to the end of the data thats already there.

When data is read from one end of the stream, the oldest data available will be read (i.e. it a stream is a FIFO).

These statements should enable you to answer all your questions, but I'll make it explicit as well:

  1. The server will only read what the client wrote, and not what it wrote itself
  2. The server will read the old stuff first and then the new stuff
  3. The client has no immediate way of knowing if the data was actually received by the other side, unless the server sends something in response. In some conditions it can know if sending failed (for example when there's a physical problem on the side of the client), but generally can't rely on that notification being there.
like image 149
Joachim Sauer Avatar answered Oct 19 '22 04:10

Joachim Sauer