Programming Windows Socket with MFC
The understanding of network fundamentals must precede any socket programming. The first 2 chapters of Computer Networking by JF Kurose and KW Ross offer all one needs to start playing sockets.
There are basically three ways to program Windows sockets:
- Use the socket functions of Windows API directly.
- Use the simplest socket class of MFC - CSocket.
- Use the powerful socket class of MFC - CAsyncSocket directly.
- Use classes derived from CAsynchSocket.
Choice 1 is language independent and has the full power of Windows sockets. However it is less friendly than MFC classes that wrap them.
Choice 2 is very simple, but very inflexible and the least powerful. It is good only for extremely simple socket use. It is rarely useful.
Choice 3 is almost as powerful as choice 1, but it is very hard to handle notifications with this choice.
Choice 4 is the best in most cases. It has both the power of Windows sockets and the ease of a class that has built-in notification handlers that can be overridden.
Since blocking socket is very vulnerable to hang, asynchronous (non-blocking) sockets are almost always preferred and this usually results in the use of notification messages. The choice 4 is the easiest way to fully utilizing the notification mechanism of Windows sockets.
One may think, as Microsoft suggests, using multi-threading may take care of hangs. However Microsoft does tell explicitly that socket class objects cannot be passed to another thread. One would have to go through the detach, attach process to pass the socket. This obviously cannot pass other information of the objects that may be very useful for user-derived socket classes. Using multi-threading is a much worse choice than using socket notification mechanism to prevent hangs.
(originally written on 5/21/02)