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. Soselect
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 andrecv
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
精彩评论