【问题标题】:Can epoll receive udp packet?epoll可以接收udp包吗?
【发布时间】:2011-09-16 04:23:52
【问题描述】:

我是网络编程的新手,听说过 epoll。我阅读了一些教程,现在我对 epoll 的作用以及如何实现它有了一些基本的了解。

问题是,即使客户端使用 udp 连接,我也可以使用 epoll 吗?我阅读的所有教程都使用了 tcp 连接。

还有没有很好的教程或示例代码来解释使用 epoll 实现基于多线程的服务器?我从网上得到的那些教程只展示了如何在单线程上创建一个简单的回显服务器。

提前致谢。

【问题讨论】:

  • 你可以在 epoll 中使用任何类型的套接字。

标签: c++ epoll


【解决方案1】:

在UDP中使用epoll没有问题,epoll只是通知文件描述符中是否有任何数据要读取。与 UDP 套接字行为相关的读/写操作有一些含义(来自 epoll 的手册页):

       For stream-oriented files (e.g., pipe, FIFO, stream socket), the condition
       that the read/write I/O space is exhausted can also be detected by
       checking the amount of data read from / written to the target file
       descriptor.  For example, if you call read(2) by asking to read a certain
       amount of data and read(2) returns a lower number of bytes, you can be
       sure of having exhausted the read I/O space for the file descriptor.  The
       same is true when writing using write(2).  (Avoid this latter technique if
       you cannot guarantee that the monitored file descriptor always refers to a
       stream-oriented file.)

另一方面,直接使用epoll不太常见。使用 epoll 的最佳方式是使用事件循环库、libev 或 libevent,例如。这是一种更好的方法,因为 epoll 并非在每个系统中都可用,并且使用这种库,您的程序更便携。

Here 你可以找到 libev 与 UDP 一起使用的示例,Here 其他示例与 libevent。

【讨论】:

    猜你喜欢
    • 2015-02-08
    • 2010-12-09
    • 2015-03-14
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    相关资源
    最近更新 更多