i am programming a tcp_ip server which intends to listen permanently to a client . the client can disconnect and connect again and the server accept it(by this point it works).The problem is when the client lose connection without a disconnect command and my code can't get it and keeps waiting for some message to come with the read command considering that socket still working. i need it to exit from read command and close the socket in order to accept another one...
I thought to use a separate thread which consider the connection lost if it doesn't read anything from the client for a certain period of time...but it seems strange to me that there's not a prepared function in some tcp library that already does it.
ANY SUGGESTMENTS? THANKS A LOT
Massimo
Here's a piece of the code:
void die(char * message)
{
perror(message);
exit(1);
}
void copyData (int from, int to)
{
while ((len = read(from, buff, sizeof(buff))) > 0)
{
interpreta_messaggio(buff);
}
close(from);
}
void main()
{
struct sockaddr_in address;
int sock, conn, i;
size_t addrLength = sizeof(struct sockaddr_in);
if ((sock = socket(PF_INET,SOCK_STREAM,0)) < 0)
die("socket");
i=1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR, &i,sizeof(i));
address.sin_family = AF_INET;
address.sin_port = htons(7000);
memset(&address.sin_addr, 0, sizeof(address.sin_addr));
if (bind(sock, (struct sockaddr *) &address, sizeof(address)))
die("bind");
if (listen(sock,5))
die("listen") ;
while (( new_socket = accept(sock, (struct sockaddr *) &address,&addrLength)) >=0)
{
copyData(new_socket,1);
}
if (new_socket < 0)
die("accept");
close(sock);
//return EXIT_SUCCESS;
}