Learning Hub Search Ctrl K

MFC › 7. Data, System and Interop

Networking with Sockets

CAsyncSocket and CSocket.

advanced #mfc#sockets#casyncsocket#csocket#winsock#tcp#afxsocketinit#networking

Explanation

MFC wraps Winsock in two classes (header <afxsock.h>):

Class Model
CAsyncSocket thin wrapper over a Winsock socket; non-blocking: it notifies you with virtual functions OnConnect, OnAccept, OnReceive, OnSend, OnClose.
CSocket derived from CAsyncSocket; synchronous: Send/Receive/Accept/Connect look blocking (internally it pumps messages so the UI stays alive). Can be tied to a CSocketFile + CArchive to stream serialized objects.

Setup: call AfxSocketInit() once (in InitInstance, or in main after AfxWinInit for console programs); it starts Winsock and returns FALSE on failure.

Typical server: Create(port) → Listen() → Accept(connectedSocket). Typical client: Create() → Connect(host, port). Then Send(buf, len) and Receive(buf, size). Receive returns the number of bytes (0 = peer closed, SOCKET_ERROR = error; check GetLastError()).

TCP is a stream, not messages: one Send may arrive as several Receives and several Sends may be merged. Add a length prefix or delimiter to your protocol.

Example

A TCP echo round-trip on the loopback address inside one program:

#include <afxwin.h>
#include <afxsock.h>
#include <iostream>

int _tmain() {
    if (!AfxWinInit(::GetModuleHandle(nullptr), nullptr, ::GetCommandLine(), 0)) return 1;
    if (!AfxSocketInit()) { std::wcout << L"Winsock failed\n"; return 1; }

    // ---- server side: listen on an OS-chosen port, on loopback only
    CSocket listener;
    if (!listener.Create(0, SOCK_STREAM, _T("127.0.0.1")) || !listener.Listen()) return 1;
    CString addr;
    UINT port = 0;
    listener.GetSockName(addr, port);                       // which port did we get?

    // ---- client side: connect (the OS queues the connection until we Accept)
    CSocket client;
    client.Create();
    if (!client.Connect(_T("127.0.0.1"), port)) {
        std::wcout << L"connect failed: " << ::GetLastError() << L"\n";
        return 1;
    }

    CSocket conn;
    listener.Accept(conn);                                  // the server's end of the connection

    const char hello[] = "hello socket";
    client.Send(hello, sizeof(hello) - 1);

    char buffer[64] = {};
    int got = conn.Receive(buffer, sizeof(buffer) - 1);     // bytes actually received
    std::cout << "server received " << got << " bytes: " << buffer << "\n";

    conn.Send(buffer, got);                                 // echo it back
    char reply[64] = {};
    got = client.Receive(reply, sizeof(reply) - 1);
    std::cout << "client received: " << reply << "\n";

    client.Close();
    conn.Close();
    listener.Close();
    return 0;
}

An event-driven client skeleton with CAsyncSocket (compiled, not run):

#include <afxwin.h>
#include <afxsock.h>

class CChatSocket : public CAsyncSocket {
public:
    CWnd* m_pOwner = nullptr;                      // where to report events
protected:
    void OnConnect(int nErrorCode) override {
        if (nErrorCode == 0) Send("HELLO\r\n", 7);
        else AfxMessageBox(_T("Connection failed"));
        CAsyncSocket::OnConnect(nErrorCode);
    }
    void OnReceive(int nErrorCode) override {      // data is waiting: read it NOW
        char buf[512];
        int n = Receive(buf, sizeof(buf));
        if (n > 0 && m_pOwner) {
            CStringA text(buf, n);
            m_pOwner->SetWindowText(CString(text));
        }
        CAsyncSocket::OnReceive(nErrorCode);
    }
    void OnClose(int nErrorCode) override {
        Close();
        CAsyncSocket::OnClose(nErrorCode);
    }
};

// usage (in a dialog, after AfxSocketInit() in InitInstance):
//   m_socket.m_pOwner = this;
//   m_socket.Create();                                   // creates the socket
//   m_socket.Connect(_T("example.com"), 80);             // returns at once; the result arrives in OnConnect

Common pitfalls

  • Forgetting AfxSocketInit() makes every call fail with a Winsock “not initialized” error.
  • Streams, not messages: a single Receive can return half a message. Loop until you have a complete message (length prefix).
  • CAsyncSocket::Connect returns FALSE with WSAEWOULDBLOCK for a normal non-blocking connect; check GetLastError() before reporting failure.
  • Socket objects are tied to the creating thread’s message pump. Passing a CSocket between threads requires Detach() / Attach() via the handle.
  • CSocket blocking calls pump messages, so the UI can re-enter your handler in the middle of a call. Disable commands while a call is in progress.
  • Calling Close() inside OnReceive then touching the socket crashes: structure the code to return right after closing.
  • Security: validate everything you read from the network (lengths, strings); never trust a length field for an allocation size.

Legacy vs modern

CSocket’s blocking-with-message-pump design is a known source of re-entrancy bugs, and MFC’s socket classes are IPv4-oriented. Modern code uses Winsock2 directly (with IPv6 and overlapped I/O or I/O completion ports), Boost.Asio / standalone Asio, or higher-level libraries (cpprestsdk, libcurl, gRPC). Use the MFC classes for existing code.

Exercises

1. Why can a single Send("ABCDEF", 6) be received as "ABC" and then "DEF"?

TCP delivers a byte stream; the network may split or merge segments. The receiver must loop and reassemble according to its own protocol framing.