Server is not able to accept() messages from multiple clients?
两个客户端能够连接到服务器,但它只接受和显示第一个客户端的输入流消息,而不是第二个客户端,尽管另一个客户端也已连接。
以下是我接受流的代码,我尝试关闭每个领带的套接字,但没有成功。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
int main(int argc,char *argv[])
{ fd_set ready; struct sockaddr_in msgfrom; int msgsize; union { uint32_t addr; char bytes[4]; } fromaddr; if ((progname = rindex(argv[0], ‘/’)) == NULL) |
这是我设置服务器的代码,供参考:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
int setup_server() {
struct sockaddr_in serv, remote; struct servent *se; int newsock, len; len = sizeof(remote); |
客户端代码:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
sock = setup_client();
/* * Set up select(2) on both socket and terminal, anything that comes * in on socket goes to terminal, anything that gets typed on terminal * goes out socket… */ while (!done) { FD_ZERO(&ready); FD_SET(sock, &ready); FD_SET(fileno(stdin), &ready); if (select((sock + 1), &ready, 0, 0, 0) < 0) { perror(“select”); exit(1); } if (FD_ISSET(fileno(stdin), &ready)) { if ((bytes = read(fileno(stdin), buf, BUF_LEN)) <= 0) done++; send(sock, buf, bytes, 0); } msgsize = sizeof(msgfrom); if (FD_ISSET(sock, &ready)) { if ((bytes = recvfrom(sock, buf, BUF_LEN, 0, (struct sockaddr *)&msgfrom, &msgsize)) <= 0) { done++; } else if (aflg) { fromaddr.addr = ntohl(msgfrom.sin_addr.s_addr); fprintf(stderr,“%d.%d.%d.%d:”, 0xff & (unsigned int)fromaddr.bytes[0], 0xff & (unsigned int)fromaddr.bytes[1], 0xff & (unsigned int)fromaddr.bytes[2], 0xff & (unsigned int)fromaddr.bytes[3]); } write(fileno(stdout), buf, bytes); } //close(sock); } return(0); } /* int setup_client() { struct hostent *hp, *gethostbyname(); /* |
- 从您发布的代码中,您的 accept 调用在您的服务器设置中,所以虽然您没有显示 setup_server 被调用的位置,但我只能假设您调用 accept 一次?如果是这样,那是你的问题。 accept() 是获取客户端连接以进行处理的内容。如果您只调用一次,您将只处理一个客户端连接。
- 你的 accept() 电话在哪里?
- @spdaley 我现在在代码段中包含了 main 方法。
UDP 没问题,你可以像你已经在做的那样 recvfrom()。
TCP 是不同的,但你快到了:你需要为你想要处理的每个连接调用 accept(),即你在循环中持有 select() 服务器套接字,调用 accept() 为有必要获得一个新的套接字,处理它并在最后关闭它。
在客户端,您似乎已连接,因为您在服务器的待处理连接队列中 – 请参阅 listen(2) 手册页。
- 我已经尝试过,但这次即使在我关闭它之后它也无法绑定套接字。供您参考,我还包括了客户端代码,请告知我到底哪里出错了。
- 您不应该关闭服务器套接字或重新绑定它;只需在同一个服务器套接字上再次调用 accept() 即可。
- 您应该关闭 accept() 返回的套接字句柄。在您准备好停止接受客户端连接之前,不要关闭服务器套接字句柄。
来源:https://www.codenong.com/13648936/