Linux C Socket: Blocked on recv call

前端 未结 2 952
不知归路
不知归路 2021-01-24 02:51

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.

相关标签:
2条回答
  • 2021-01-24 03:11

    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.

    0 讨论(0)
  • 2021-01-24 03:13

    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.

    0 讨论(0)
提交回复
热议问题