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 destAddr
fields)
Using the socket for send()
/recv()
operation:
send(sockDesc, buffer, bufferLen, 0)
recv(sockDesc, buffer, bufferLen, 0)
close()
the socket descriptor and exit
close(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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…