In my client code, I am following these steps to connect to a socket:
-
Creating a socket
sockDesc = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) -
Connecting it (retry for ‘x’ time in case of failure)
connect(sockDesc, (sockaddr *) &destAddr, sizeof(destAddr))(After filling the
destAddrfields) -
Using the socket for
send()/recv()operation:send(sockDesc, buffer, bufferLen, 0) recv(sockDesc, buffer, bufferLen, 0) -
close()the socket descriptor and exitclose(sockDesc)
If during send()/recv() the connection breaks, I found that I could connect by returning to step 2.
Is this solution okay? should I close the socket descriptor and return to step 1?
Another interesting observation that I am not able to understand is when
I stop my echo server and start the client. I create a Socket (step 1) and call connect() which fails (as expected) but then I keep calling connect(), lets say, 10 times. After 5 retries I start the server and connect() is successful. But during the send() call it receives SIGPIPE error. I would like to know:
1) Do I need to create a new socket every time connect() fails? As per my understanding as long as I have not performed any send()/recv() on the socket it is as good as new and I can reuse the same fd for the connect() call.
2) I don’t understand why SIGPIPE is received when the server is up and connect() is successful.
Yes, you should close and go back to step 1:
From here.