gpt4 book ai didi

c - 使用 epoll 处理多个 TCP 连接上的数据

转载 作者:可可西里 更新时间:2023-11-01 02:47:48 24 4
gpt4 key购买 nike

我有一个应用程序,它将像 p2p 软件一样工作,所有对等方都将相互交谈。由于通信将是 TCP,我认为我可以使用 epool(4)以便可以处理多个连接。由于每个对等点都会非常频繁地发送数据,我想我将与每个对等点建立一个持久连接,在应用程序生命周期内使用。

现在,我不知道如何处理的一件事是,由于连接永远不会关闭,我怎么知道什么时候应该停止使用 read() 接收数据并调用 epool_wait() 再次收听更多包后?或者是否有更好的方法来处理持久的 TCP 连接?

最佳答案

应该设置socket为非阻塞的,当epoll指示有数据可读时你应该在循环中调用 read() 直到 read() 返回 -1 并且 errno 是 EWOULDBLOCK

也就是说,您的读取循环可能看起来像这样:

for(;;)
ssize_t ret;
ret = read(...);
if(ret == 0) {
//client disconnected, handle it, remove the fd from the epoll set
break;
} else if(ret == -1) {
if(errno == EWOULDBLOCK) {
// no more data, return to epoll loop
} else {
//error occured, handle it remove the fd from the epoll set
}
break;
}

// handle the read data
}

如果你不使用 epoll 的边沿触发模式,你真的不需要循环——你可以只做 1 次读取并返回到 epoll 循环。但是像上面的代码一样处理返回值。

关于c - 使用 epoll 处理多个 TCP 连接上的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2371862/

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