我正在尝试创建一个服务器/客户端程序,客户端将文本“Hello World”发送到服务器,然后服务器将文本打印到终端。
客户端程序终止后服务器发疯并继续打印“Hello World”,直到我通过Ctrl-C终止服务器。有人可以帮我理解原因吗?
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);
}
答案 0 :(得分:2)
read(i, buf,11);
buf[11] = '\0';
您忽略了read()的返回码。如果为零,则对等体已断开连接,您必须关闭套接字。如果是正数,则是接收的字节数。所以第二行中的'11'应该是'count'或者你收到返回代码的变量被调用的任何内容。你不能假设你有11个字节。