开发者

How to detect connection closed by localhost?

开发者 https://www.devze.com 2023-04-03 03:30 出处:网络
I have write a TCP client and server in C. These software run on the same computer ONLY. 1) My TCP client send a command to the server (localhost).

I have write a TCP client and server in C. These software run on the same computer ONLY.

1) My TCP client send a command to the server (localhost).

2) The server works hard and give a response.

The problem is if the TCP Client closes the connection, I am unable to detect a client connection closed WHILE server is going to do its long work. I 开发者_运维技巧can only detect this with the SEND function, but it's too late because the server have already work.

I understand that this must be very hard to make this detection if the machines are remote. In my case, it is the same machine, which should make the task easier, but I have not found a solution ... Can be with the select function?

Thanks you.


You can do it with select like this:

  • Use select for read events on the socket. So select unblocks when the socket is readable
  • When a request arrives at the server, start work in a different thread
  • When the client closes the connection, select will unblock and recv will read 0 bytes. If so, you can stop the worker thread
  • If the worker thread finishes the task without being interrupted, it can send the result
0

精彩评论

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

关注公众号