Server is strange after client disconnected
I'm trying to make a server/client program where the client sends the text “Hello World” to the server, the server then prints the text to the terminal.
After the client program terminates the server goes crazy and keeps printing “Hello World” until I terminate the server by Ctrl – C. Can someone please help me to understand why?
selectserver.c
#include <sys/types.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
main()
{
struct sockaddr_in serveraddr, clientaddr;
int clientaddrlen;
int request_sock, sock[2], numsocks, maxsocks;
char buf[12];
int i, rc;
fd_set fds, readfds;
struct timeval timeout;
numsocks = 0; maxsocks = 2;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
request_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bzero((void *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = INADDR_ANY;
serveraddr.sin_port = htons(2009);
bind(request_sock, (struct sockaddr *)&serveraddr, sizeof serveraddr);
listen(request_sock, SOMAXCONN);
FD_ZERO(&fds);
FD_SET(request_sock, &fds);
for (;;) {
readfds=fds;
rc=select (FD_SETSIZE, &readfds, NULL, NULL, &timeout);
if (rc<0)
return -1;
for (i = 0; i < FD_SETSIZE; i++)
if (FD_ISSET (i, &readfds)) {
if (i == request_sock) {
if(numsocks < maxsocks) {
sock[numsocks] = accept(request_sock,(struct sockaddr *)&clientaddr, (socklen_t *)&clientaddrlen);
FD_SET(sock[numsocks], &fds);
numsocks++;
} else {
printf("Ran out of space for sockets.\n");
return -1;
}
} else {
read(i, buf,11);
buf[11] = '\0';
开发者_开发技巧 printf("From socket %d: %s\n",i,buf);
}
}
}
close(request_sock);
}
selectclient.c
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
main(int argc, char *argv[])
{
struct sockaddr_in serveraddr;
int sock;
char buf[12];
int i;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bzero((void *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr("192.168.1.3");
serveraddr.sin_port = htons(2009);
connect(sock, (struct sockaddr *)&serveraddr, sizeof serveraddr);
for(i=0; i<10; i++) {
write(sock, "Hello World", 11);
sleep(1);
}
close(sock);
}
read(i, buf,11);
buf[11] = '\0';
You are ignoring the return code of read(). If it is zero, the peer has disconnected and you must close the socket. If it is positive, it is the number of bytes received. So '11' in the second line should be 'count' or whatever the variable is called that you received the return code into. You can't assume you got all 11 bytes.
精彩评论