Sign in to follow this  

[WinSock2] Windows Asynchronous Sockets vs Non-Blocking Threaded Sockets

Recommended Posts

Ameise    1148
Quick query -- is there a signifigant difference between using Windows Asynchronous sockets (besides the fact that they are Windows only) and running a non-blocking socket on a separate thread? I am leaning towards the latter being better as it is portable, though I am also thinking that Windows Asynch sockets might be faster as they are closer to driver-level.

Share this post

Link to post
Share on other sites
Neither is really the best way if Windows is your target platform, although asynchronous sockets are better.

Non-blocking sockets require you to burn CPU cycles on polling and at the same time may not be 100% reliable (for example, if you don't poll often enough on a UDP socket, you WILL lose data as the buffers fill up). It does work, but it is neither elegant, nor efficient. If you're already using a separate thread anyway, you could as well have it block. That way, it won't burn CPU for spinning, and it will be more reliable.

Asynchronous sockets, in principle, are a good way, but the Winsock implementation of select() or its WSA counterpart kind of suck ass. It is (like WaitForMultipleObjects, which is probably what it builds on, internally) not very performant and limited to max. 64 total handles.
Nevertheless, if you only have one or two connections and if you want your code to be somewhat portable, it is certainly the way to go (I say "somewhat portable" because Winsock is different enough from normal socket API so you have to plan for that ahead in time and define a few wrappers -- for example closesocket becomes close under real sockets, and INVALID_SOCKET is not defined -- there are 5 or 6 little peculiarities like that, all of which a few #ifdef #define statements can take care of).

If portability is not really required, use overlapped sockets with an IO completion port. IOCP are the kqueue/epoll equivalent for Windows, they are very efficient (20.000 connections are not an issue if you need that many) and very straightforward.
All you really need to do for it to work is to pass a non-null OVERLAPPED structure to all Winsock functions and associate your socket with the completion port, which is maybe half a dozen lines of code total. Then you can let the work happen somewhere in the background (you don't need to care!) and you can query or wait for completion at any time.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this