How to set sockets to blocking mode in Windows?

2019-02-15 00:03发布

I'm doing some fairly simple cross-platform TCP socket programming. I have unfortunately found out that when compiled on Windows, my sockets are non-blocking by default, while on OS X they are blocking by default. How do I force a socket into blocking mode on Windows? Do they normally default to non-blocking mode or is something terribly wrong?

My code is based in part on these simple examples: http://cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoClient.c http://cs.baylor.edu/~donahoo/practical/CSockets/code/TCPEchoServer.c

2条回答
我命由我不由天
2楼-- · 2019-02-15 00:34

No, plain old BSD style sockets are not non-blocking by default on Windows. See the examples in the Winsock Programmer's FAQ.

If you use MFC and its CAsyncSocket mess, then yes, it's all non-blocking, but that's a separate issue.

查看更多
甜甜的少女心
3楼-- · 2019-02-15 00:47

I believe this reference may help; note, in particular, that

Although blocking operations on sockets are supported under Windows Sockets, their use is strongly discouraged. Programmers who are constrained to use blocking mode -- for example, as part of an existing application which is to be ported -- should be aware of the semantics of blocking operations in Windows Sockets.

If you're fully aware of the zillion issues listed here, and find dealing with all of them preferable to designing your program to fit in well with Windows rather than being a half-beeped port from Unix, go right ahead with a ioctlsocket call with the cmd argument set to FIONBIO and the third argument pointing to a longword worth 0. But, don't say you weren't warned;-).

查看更多
登录 后发表回答