开发者

Why we need to read() before write() in TCP server program?

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


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).


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜