Reputation: 4338
This works for me now . But then i have to make sure reconnect by client is started after sometime say two minute . As starting client again takes a little while and address already in use is thrown. But after a minute it is allowed to bind and listen which was not happening. Is this TTL time i need to wait ?
I wrote a server socket program in which I have server and client running on same host . The server only writes (no read operation by server) while client only reads from server ( no write done by client). When I kill server process and try to run again it says Address already in Use. When using SO_REUSEADDR it allows me to reuse the port but client no more receives data from server. Part of server code
while(1)
{
write(newsockfd,"I got your message",18); //Server Publishes data all day
}
part of client code:-
while(1)
{
n = read(sockfd,buffer,255);//Read all server publishes and store them
if (n == 0)
error("ERROR reading from socket");
printf("Here is the message: %s \n",buffer);
bzero(buffer,256); //Buffer set to Null again
}
If on connection I try netstat -a I can see my server listening to port say 20001 to which i bind it. But I cannot still see establish connection even when both client ans server are running . Client keeps printing data received from server. As I kill server process, I see client just printing newline as buffer set to NULL after every read. Now my question is if there is connection already establish which is now terminated does this prevents Server from listening on same port ? My main Question If so why is no other process listening to that port ? SO_REUSEADDR allows server to bind and REUSE ADDR . Is this because Server and client running on same host ? How to handle in case the termination is ungraceful (secondary question). After adding read check as in comment I still see client running and netstat gives me below output:-
xyz@xyz:~$ netstat -a | grep -i 2001
tcp 0 0 localhost:47058 localhost:2001 CLOSE_WAIT
tcp 0 0 localhost:2001 localhost:47058 FIN_WAIT2
Thanks in advance
Upvotes: 1
Views: 1707
Reputation: 3541
. When i kill server process and try to run again it says Address already in Use. When using SO_REUSEADDR it allows me to reuse the port but client no more receives data from server.
You cannot have your client continue as if nothing happened to server . Client should detect broken connection and do socket close from its end and restart the connection establishment process all over again. Old connection is gone for good.
Upvotes: 0
Reputation: 84189
Looks like you are a bit confused about how TCP works.
When you terminate and re-start the server, the client is no longer connected, so it needs to close its end of the TCP connection, i.e. call close(2)
on the socket descriptor, then create a new socket(2)
and connect(2)
it again.
You are probably missing 0 (zero) returned from the read(2)
on the client socket that means the other end has closed its end of the connection.
Upvotes: 1