Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does reading from a socket wait or get EOF?

I'm implementing a simple connection between a client and a server in C. In client side, I'm in a loop, reading from a file; every time BUFFER_SIZE bytes and sending it to the server side (didn't upload error handling).

//client side
bytesNumInput = read(inputFileFD,bufInput,BUFFER_SIZE)
bytesSend = write(sockfd,bufInput,bytesNumInput)

Of course the server is also in a loop.

//server side
bytesRecv = read(sockfd,bufOutput,bytesNumInput)

Now, my questions are:

  1. Can I get EOF in the middle of the connection if the server reads faster than the client?
  2. Does the read function wait to get all the data or is it the same as reading from a file?
  3. Is it possible the server will handle 2 read iteration in 1 write iteration?
like image 426
Paz Avatar asked Feb 12 '17 13:02

Paz


People also ask

How does socket read work?

Behavior for sockets: The read() call reads data on a socket with descriptor fs and stores it in a buffer. The read() all applies only to connected sockets. This call returns up to N bytes of data. If there are fewer bytes available than requested, the call returns the number currently available.

What is EOF in socket?

End Of File (-EOF) The End Of File (-EOF) adapter command defines a single message. The adapter uses this command when communicating with other programs that invoke and detect calls to the shutdown function as defined by the Socket Application Programming Interface (API).

Is socket communication fast?

Sockets are faster than web services in general.

Can sockets send and receive?

Once connected, a TCP socket can only send and receive to/from the remote machine. This means that you'll need one TCP socket for each client in your application. UDP is not connection-based, you can send and receive to/from anyone at any time with the same socket.


1 Answers

Can I get EOF in the middle of the connection if the server reads faster than the client?

No. EOF means the peer has disconnected. If the connection is still alive, read() will block until (a) at least one byte is transferred, (b) EOF occurs, or (c) an error occurs.

Does the read function wait to get all the data or is it the same as reading from a file?

See (a) above.

Is it possible the server will handle 2 read in 1 write iteration?

Yes. TCP is a byte-stream protocol, not a messaging protocol.

like image 127
user207421 Avatar answered Oct 11 '22 13:10

user207421