gpt4 book ai didi

c - 接受多个客户的正确方法?

转载 作者:太空宇宙 更新时间:2023-11-04 04:12:24 25 4
gpt4 key购买 nike

我正在从事一个涉及多线程服务器的项目,理论上应该能够同时接受任意数量的客户端。每次客户端连接到服务器时,都需要生成一个新线程来满足客户端的需求。我很困惑 listen() 函数是否起到了任何作用。这是否需要处于无限循环中?我应该一次只监听一个客户端连接吗?

当我调用 listen 函数时,我传递了套接字文件描述符和连接数,在我的例子中,我传递了 5。我不在循环或任何其他地方运行它,我只调用它一次。但是,考虑到我需要的实现,我认为这不是正确的方法

// now the server can listen
int listennum = listen(socketfd, 5);
if (listennum != 0) {
printf("Listen has failed..\n");
exit(0);
}
else {
printf("Server is listening..\n");
}

最佳答案

I am confused whether the listen() function plays any part of this. Does this need to be in an infinite loop?

没有。 listen() 设置套接字的属性,将其标记为被动套接字,程序可以通过该套接字接受连接。没有必要多次这样做。不要忘记首先 bind() 套接字(您也应该只执行一次)。

Should I only be listening for one client connection at a time?

这并不是套接字接口(interface)提供的真正概念,尽管有一个相关的概念,即有多少等待接受的连接可以同时排队等待套接字。这由 listen() 的第二个参数控制。

When I call the listen function, I pass the socket file descriptor and the number of connections, which in my case, I pass 5. I do not run this in a loop or anything, I just call it once.

这正是您应该做的,但这不是唯一您应该做的事情。

However, I do not think this is the proper way to do it considering the implementation I need

您可能错过了在调用 listen() 之后,您必须使用 accept() 函数来实际接受连接。 就是您要在循环中运行的内容。您可以接受来自同一个监听套接字的任意数量的连接。

关于c - 接受多个客户的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55753640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com