Programming Windows Socket with MFC
The understanding of network fundamentals must precede any socket programming. The first two chapters of Computer Networking by JF Kurose and KW Ross offer all one needs to start playing with sockets.
There are basically three ways to program Windows sockets:
- Use the socket functions of the 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 the 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 sockets are very vulnerable to hanging, asynchronous (non-blocking) sockets are almost always preferred, and this usually results in the use of notification messages. Choice 4 is the easiest way to fully utilize the notification mechanism of Windows sockets.
One may think, as Microsoft suggests, that using multi-threading may take care of hangs. However, Microsoft explicitly states 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 about the objects that may be very useful for user-derived socket classes. Using multi-threading is a much worse choice than using the socket notification mechanism to prevent hangs.