Winsock MSG_DONTWAIT 等效项 [英] Winsock MSG_DONTWAIT equivalent

查看:61
本文介绍了Winsock MSG_DONTWAIT 等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows 下移植 unix C++ 代码并使用套接字/winsock API 时,我在服务器端遇到了这个问题:

While porting unix C++ code under windows and using sockets/winsock API, I am confronted with this on the server side:

recv(ClientSocket, recvbuf, recvbuflen, MSG_DONTWAIT); // UNIX code

我从这里找到 与 WSA 的 MSG_DONTWAIT 标志等效的是使用 ioctlsocket 将套接字设置为非阻塞模式:使用 arg != 0 调用 FIONBIO (这里是文档).

I found from here that the equivalent of the MSG_DONTWAIT flag with WSA is to set the socket in nonblocking mode with ioctlsocket: call FIONBIO with arg != 0 (here is the documentation).

在服务器端,我有两个套接字:

Being on the server side, I have though two sockets:

  • 连接服务器的socket:

  • The socket for connecting to server:

SOCKET ListenSocket = socket(...)
bind(ListenSocket, ...)
listen(ListenSocket, ...)
...

  • 用于接受来自客户端的连接的临时套接字:

  • The temporary socket for accepting connections from clients:

    SOCKET ClientSocket;
    ClientSocket = accept(ListenSocket, ...)
    recv(ClientSocket, ...)
    ...
    

  • 我用哪个套接字调用 ioctlsocket ?在哪里?(我的意思是这些步骤在哪里?)

    Which socket do I call ioctlsocket with? And where? (I mean where wrt these steps?)

    推荐答案

    ListenSocket 顾名思义就是侦听传入 (TCP/IP) 连接的套接字,并且仅用于此目的.你稍后在该套接字上调用 accept().accept() 返回另一个套接字,一旦有传入连接.这是 ClientSocket这将用于发送/接收数据到/从.这也是插座需要进入非阻塞模式才能模拟MSG_DONTWAIT 的行为(特定于 Linux,不要现在就知道 POSIX 是否也定义了这一点).

    The ListenSocket is as the name implies the socket listening on incoming (TCP/IP) connections and serves only that purpose. You call accept() later on that socket. accept() returns another socket, as soon as there is an incoming connection. This is the ClientSocket which will be used to send/recv data to/from. It is also the socket that needs to be put into non-blocking mode in order to emulate the behaviour of MSG_DONTWAIT (which is specific to Linux, don't know right now if POSIX defined this also).

    所以,简而言之,在accept之后和recv之前调用ioctlsocket客户端套接字.

    So, put short, call ioctlsocket after accept and before recv on the ClientSocket.

    注意:如果你再次调用accept(),你也可以有多个连接,每个连接都有一个由accept()返回的单独套接字.你然后会使用 select() 之类的东西来复用 I/O.

    Note: If you call accept() again you can also have more than one connection, each with a seperate socket returned by accept(). You then would use something like select() to multiplex I/O.

    这篇关于Winsock MSG_DONTWAIT 等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆