Reputation: 106
I've written a socket server program that sends a message to the client every 200ms in one thread (fork child process) and waits for getting data from the client in another thread. the problem is, if the server connection disconnected, no error won't raise. I've tried using signals (SIGPIPE) and checking errrno variable.
When I disconnect my server hotspot, data send to socket and no error display.
here's the code:
int ListeningForConnection(int Sockfd) {
int clilen = sizeof(Cli_addr);
int SocketId;
while(1) {
printf("waiting for new client...\n");
if ((SocketId = accept(Sockfd, (struct sockaddr *)&Cli_addr, (socklen_t *)&clilen)) < 0) {
printf("%s", "ERROR on accept. errno:%d : %s\n", errno, strerror(errno));
close(Sockfd);
return
}
printf("opened new communication with client\n");
if (fork() == 0)
SendDataToClient(SocketId);
else
GetDataFromClient(SocketId);
// if any error happen, should waiting for new client to connect.
}
return 0;
SendDataToClient:
while(1) {
int n;
if ((n = send(socket, SendData ,strlen(SendData), MSG_CONFIRM)) < 0) {
printf("%s\n", "ERROR writing to socket");
return;
}
printf ("%s No:%d %s \n ",SendData,n,strerror(errno));
delay(200);
}
Upvotes: 0
Views: 728
Reputation: 123260
When I disconnect my server hotspot, data send to socket and no error display.
The fault is not your program but your expectations.
TCP is robust against temporary disrupting the connectivity between the client and server application, and this is what you actually do when disconnecting the hotspot. TCP will recover from this once the connectivity is established again, i.e it will buffer unacknowledged data locally and retry sending these for some time.
I've tried using signals (SIGPIPE) and checking errrno variable.
Errors and/or SIGPIPE will happen if the TCP connection is actually closed but not on temporary disruptions. Closing can be done explicitly by either client or server or it can be done implicitly if unrecoverable delivery problems are detected, for example due to timeout or because of TCP keep-alive. If this is not (yet) the case the write to the socket will either succeed directly or the writing will block (if the socket is blocking) if no more space is inside the socket buffer.
For early detection of disrupted connectivity on idle connections use TCP keep-alive. For detecting problems delivering data use timeout for unacknowledged data.
Upvotes: 2