Linux C Socket: Blocked on recv call

不想你离开。 提交于 2019-12-02 04:06:16
Tanmoy Bandyopadhyay

You have told "In my application i have created a thread for a simple http server, then from within my application i tried to connect to http server but control is blocked/hanged on recv call."

That means the recv is never returning 0. Now when the recv function will return a 0? ->When it gets a TCP FIN segment. It seems that your server is never sending a TCP FIN segment to the client. The reason that is most likely here is that, your client code needs modification. You are sending data from from the client, but you are never sending the FIN, so I assume that your server function is continuing forever and it had not sent the FIN. This made the recv wait for ever.

In the current code perhaps the fix is to add a line

else {
  /*Send the FIN segment, but we can still read the socket*/
  shutdown(s, SHUT_WR); 
  /* read result & check */
  ret=http_read_line(s,header,MAXBUF-1);

In this case the shutdown function sends the TCP FIN and the server function can return and possibly then it would do a proper close.

And on a proper close, the FIN from the server will be received by the client. This would make the recv return 0, instead of getting blocked for ever.

Now if you want to continue any further data transfer from the client, you need to again connect or may be you need to have some different algorithm.

I hope my explanation may help fix the current problem.

You need to either send an HTTP 1.0 header, or else read about content-length in HTTP 1.1. You are reading the stream to EOS when the server is under no obligation to close the connection, so you block. The Content-Length header tells you how much data is in the body: you should only try to read that many bytes.

If you specify HTTP 1.0 (and no fancy headers) the server will close the connection after sending the response.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!