views:

61

answers:

4

Hi,

As per my understanding a simple TCP server will be coded as follows.

socket() - bind() - listen() - accept() - read() - write()

The clients will be written as follows.

socket() - bind()(Optional) - connect() - write() - read()

Please note the order difference in read() and write() calls between client and server program.

Is it a requirement to always read() before write() in a server program and if, then why?

Thanks, Naga

+1  A: 

You can perform them in either order. However, a server will normally generate a response from the read() operation, then write it with the write() operation, so this order makes sense.

If you're handling multiple clients, you should use a multiplexer like select to notify you when clients have data ready to read, so your server won't lock up the every time you try to read() from a client who hasn't sent anything.

lunixbochs
+2  A: 

That isn't mandatory, but it makes sense for the server to read the request before writing a response. Note that it is necessary to read on both sides often enough to prevent a distributed deadlock: for example, if the both sides are trying to write and not reading, then the buffers in-between will get full and neither one's write will be able to proceed. One solution for this is to have a separate thread which keeps reading, if there is something to read (this applies to both the client and the server).

abc
+1 for the good advice.
Ninefingers
+2  A: 

The simple answer is no. You are free to do whatever you like.

However, I'll caveat that quickly with the fact that most protocols are designed to wait for the client to send something. After all, the server, by nature, serves requests and needs to wait to know what that request is, be it "GET /" or "HELO" or whatever. So, it is fairly natural for a sever to read before writing any response back to the client.

That said, you could if you felt like it dump version information down to the client before you do any reading. To see the effect, connect to your server using telnet.

Ninefingers
In fact there are plenty of protocols where the server sends a banner or welcome message immediately upon client connect - SSH, SMTP, POP3 and IMAP come to mind.
caf
A: 

It isn't a requirement, server program can write to socket without reading first. But in many cases server program must know what client wants - so it calls read() first.

Bohdan