将Windows套接字程序移植到Unix:unix中winsock32 API的替代方案
在Socket编程中,如果连接关闭,Unix线程如何从客户端接收Socket CLOSE事件?
是否有任何 API 可以通知 unix 线程收到的 CLOSE 事件?
与在 Windows 中一样,我们有 WSAEnumNetworkEvents API,它可以获取指定套接字描述符的事件通知。 Unix 套接字编程中使用的等效 API 是什么?
请提供查询帮助。
In Socket Programming, how will a Unix thread receive a Socket CLOSE event from a client if connection is closed?
Are there any API's which will notify the unix thread about the CLOSE event received?
As in Windows we have WSAEnumNetworkEvents API which gets the event notification for a specified socket descriptor. What will be the equivalent API used in the Unix socket programing?
Please provide the help for the query.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在执行读取时跟踪关闭事件。当
read
返回0时,套接字被关闭(当然是指“Berkeley套接字”)。//编辑:
使用
poll
或select
等待某些事件发生(数据到达、套接字关闭...)。You can track the closure event when performing reading. The socket is closed when
read
returns 0 (talking about "Berkeley sockets" of course).//EDIT:
Use
poll
orselect
to wait for some event to occur (data arrival, socket closure ...).抱歉,没有时间回答,但请查看 Beej 网络编程指南
Sorry no time for an answer, but check out Beej's Guide to Network Programming
您是否考虑过使用 boost:: asio,这样你至少可以在linux和asio之间共享代码。视窗。与裸套接字相比,开销并没有那么大,并且您可以享受更好的语义的好处。 boost的很多代码都已经飞入标准C++,因此代码质量相当高。
这涉及重写您的软件,这可能不是一个选择。另一方面,您将需要维护一个通用的代码库。
Did you think about using boost::asio, this way you can share at least the code between linux & windows. The overhead is not that big compared to naked sockets and you have the benefit of better semantics. Many parts of code from boost have flown into standard C++ so the code is of rather high quality.
This involves rewriting your software what might not be an option. On the other hand you would have a common codebase to maintain.
libevent 将允许您在套接字上有数据或套接字需要时接收事件被关闭。更具体地说,您希望设置套接字以通知您读取事件 (EV_READ),并在函数回调中检查 recv 的返回值是否为 0(表示另一端的套接字已完全关闭)或 -1(表示另一端的套接字已完全关闭)一个错误。在第一种情况下,返回值为 0,您想要关闭套接字。在第二种情况下,返回 -1 表示某种“错误”,您要做什么取决于错误的性质。例如,recv 可能返回 -1 并将 errno 设置为 EINTR,指示该函数被中断,例如通过 SIGUSR1 中断。如何处理取决于您的应用程序需要做什么。
libevent will allow you receive an event when there is data on the socket or when the socket needs to be closed. More specifically, you want to setup the socket to notify you on a read event (EV_READ) and in the function callback check if the return value from recv is 0 which indicates that the socket at the other end has shutdown cleanly or -1 which indicates an error. In the first case, where the return value is 0, you want to close the socket. In the second case, where the return of -1 indicates some sort of 'error', what you do depends on the nature of the error. For example recv may return -1 and set errno to EINTR indicating that the function was interrupted, for example via a SIGUSR1 interrupt. How you handle that depends on what your application needs to do.