UDP Send and Receive Using CAsyncSocket

CK CK 3788 
Created at
Updated at  
1,207 0 0

The following is sample code showing use of CAsyncSocket to send and receive UDP packets. I used the ClassWizard to create a class (CUDPSocket) derived from CAsyncSocket. The derived class does little more than override OnReceive. The derived class is used in the application's document.
 

Sample Code


File stdafx.h

#pragma once

#define VC_EXTRALEAN
#include <afxwin.h>
#include <afxsock.h>
#include <afxcmn.h>



File UDPSocket.h

class CSendReceiveDocument;

class CUDPSocket : public CAsyncSocket
{
public:
    CSendReceiveDocument *m_pDocument; // public for debugging
    CUDPSocket() : m_pDocument(NULL) {};
    virtual ~CUDPSocket() {};
    void SetDocument(CSendReceiveDocument *pDocument) {m_pDocument=pDocument;};
    void Close() {CAsyncSocket::Close();};

    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CUDPSocket)
    public:
    virtual void OnReceive(int nErrorCode);
    //}}AFX_VIRTUAL

    // Generated message map functions
    //{{AFX_MSG(CUDPSocket)
        // NOTE - the ClassWizard will add and remove member functions here.
    //}}AFX_MSG
};



File UDPSocket.cpp

void CUDPSocket::OnReceive(int nErrorCode)
{
    CString IPAddress;
    char Buffer[512]; // Increase size as needed
    CString Message;
    DWORD Error;
    UINT Port;
    int Size;
    CAsyncSocket::OnReceive(nErrorCode);
    if (nErrorCode)
    {
        Message.Format("OnReceive nErrorCode: %i", nErrorCode);
        AfxMessageBox(Message);
        return;
    }
    Size = ReceiveFrom(Buffer, sizeof Buffer, IPAddress, Port);
    if (!Size || Size == SOCKET_ERROR)
    {
        Error = GetLastError();
        Message.Format("ReceiveFrom error code: %u", Error);
        AfxMessageBox(Message);
        return;
    }
    if (m_pDocument)
        m_pDocument->OnReceive(Buffer, Size, IPAddress, Port);
    else
        AfxMessageBox("No document pointer");
}



I am using class CSocketAddressIn to simplify use of addresses. The following is the definition.

class CSocketAddressIn : sockaddr_in
{
public:
    CSocketAddressIn()
        {ZeroMemory(this, sizeof sockaddr_in);sin_family = AF_INET;};
    CSocketAddressIn(u_long Address, u_short Port = 0);
    void SetAddress(u_long Address) {sin_addr.s_addr = htonl(Address);};
    void GetAddress(CString &s) {s=inet_ntoa(sin_addr);};
    void SetPort(u_short Port) {sin_port = htons(Port);};
    operator sockaddr *() const {return (struct sockaddr *)this;}
};



The following is the implementation of the extra constructor:

CSocketAddressIn::CSocketAddressIn(u_long Address, u_short Port)
{
    sin_family = AF_INET;
    sin_addr.s_addr = htonl(Address);
    sin_port = htons(Port);
    ZeroMemory(sin_zero, sizeof sin_zero);
}



The CSendReceiveDocument definition is:

class CSendReceiveDocument : public CDocument
{
protected:
    DECLARE_DYNCREATE(CSendReceiveDocument)

    CUDPSocket m_UDPSocket;
    int m_DataSize;
    UINT m_rSocketPort;
    CString m_rSocketAddress;
    static const CString m_NoPath;
    CString m_Message, m_ReceivedData;
    CTime m_TimeReceived;

    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CSendReceiveDocument)
    public:
    virtual BOOL OnOpenDocument(LPCTSTR lpszPathName);
    virtual void OnCloseDocument();
    virtual BOOL OnNewDocument();
    virtual void DeleteContents();
    virtual void SetPathName(LPCTSTR lpszPathName, BOOL bAddToMRU = TRUE);
    protected:
    virtual BOOL SaveModified();
    //}}AFX_VIRTUAL

public:
    CSendReceiveDocument();
    virtual ~CSendReceiveDocument() {};
    void SendTo(LPCTSTR, DWORD, LPCTSTR);
    void OnReceive(void * const, int, const CString, UINT);
#ifdef _DEBUG
    virtual void AssertValid() const;
    virtual void Dump(CDumpContext& dc) const;
#endif

// Generated message map functions
protected:
    //{{AFX_MSG(CSendReceiveDocument)
    //}}AFX_MSG
    DECLARE_MESSAGE_MAP()
};



The CSendReceiveDocument implementation is:
 

const CString CSendReceiveDocument::m_NoPath = "None";

CSendReceiveDocument::CSendReceiveDocument() : m_DataSize(0), m_rSocketPort(0) {
    CString Path;
    m_UDPSocket.SetDocument(this);
    CSocketAddressIn SocketAddressIn(INADDR_ANY);
    SocketAddressIn.GetAddress(Path);
    Path += " : 0";
    SetPathName(Path);
}

BOOL CSendReceiveDocument::OnOpenDocument(LPCTSTR lpszPathName)
{
    CString ErrorMessage, Message, PathName(lpszPathName), SocketAddress, s;
    int ColonIndex;
    UINT Port(0);
    long Events;

    OnCloseDocument();
    if (PathName == m_NoPath)
        return TRUE;
    ColonIndex = PathName.Find(':');
    if (ColonIndex == -1)
        SocketAddress = PathName;
    else {
        SocketAddress = PathName.Left(ColonIndex);
        s = PathName.Mid(ColonIndex+1);
        s.TrimLeft();
        Port = strtoul(s, NULL, 10);
    }
    Events = FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE;
    if (!m_UDPSocket.Create(Port, SOCK_DGRAM, Events, SocketAddress))
    {
        GetErrorMessage(GetLastError(), ErrorMessage);
        Message.Format("The socket for %s was not created: %s",
            PathName, ErrorMessage);
        AfxMessageBox(Message);
        SetPathName(m_NoPath);
        m_Message = "Open failed";
        UpdateAllViews(NULL, 8, NULL);
        return FALSE;
    }
    SetPathName(PathName);
    m_Message = "Opened: ";
    m_Message += PathName;
    UpdateAllViews(NULL, 1, NULL);
    SetModifiedFlag(TRUE);
    return TRUE;
}

void CSendReceiveDocument::OnCloseDocument()
{
    m_UDPSocket.Close();
    // CDocument::OnCloseDocument(); // Don't call; will close view and frame
    DeleteContents();
    SetModifiedFlag(FALSE);
}

BOOL CSendReceiveDocument::OnNewDocument()
{
    AfxMessageBox("Sorry, "New Document" is not available");
    return CDocument::OnNewDocument();
}

void CSendReceiveDocument::DeleteContents()
{
    m_DataSize = 0;
    m_Message.Empty();
    m_ReceivedData.Empty();
    UpdateAllViews(NULL, 9, NULL);
    SetTitle(m_NoPath);
    CDocument::DeleteContents();
}

void CSendReceiveDocument::SetPathName(LPCTSTR lpszPathName, BOOL bAddToMRU)
{
    m_strPathName = lpszPathName;
    ASSERT(!m_strPathName.IsEmpty()); // must be set to something
    m_bEmbedded = FALSE;
    SetTitle(lpszPathName);
}

void CSendReceiveDocument::OnReceive(void *const Buffer, int Size,
        const CString rSocketAddress, UINT rSocketPort)
{
    m_rSocketPort = rSocketPort;
    m_rSocketAddress = rSocketAddress;
    m_DataSize = Size;
    m_TimeReceived = CTime::GetCurrentTime();
    memcpy(m_ReceivedData.GetBuffer(Size), Buffer, Size);
    m_ReceivedData.ReleaseBuffer(Size);
    UpdateAllViews(NULL, 2, NULL);
}

void CSendReceiveDocument::SendTo(LPCTSTR Data, DWORD dwAddress, LPCTSTR Port)
{
    CSocketAddressIn SocketAddress;
    CString ErrorMessage, Message;
    int rv;

    SocketAddress.SetAddress(dwAddress);
    SocketAddress.SetPort((u_short)strtoul(Port, NULL, 10));
    rv = m_UDPSocket.SendTo(Data, strlen(Data), SocketAddress, sizeof SocketAddress, 0);
    if (rv == SOCKET_ERROR)
    {
        GetErrorMessage(GetLastError(), ErrorMessage);
        Message.Format("The data was not sent: %s", ErrorMessage);
        AfxMessageBox(Message);
        m_Message = "Send failed";
    }
    else
        m_Message = "Data sent";

    UpdateAllViews(NULL, 8, NULL);
}

BOOL CSendReceiveDocument::SaveModified()
{
    return TRUE;
}
Tags Client/Server Datagram SOCK_DGRAM UDP UDP Receive UDP Send Facebook X
Comments 0
Similar posts
  1. Creating and Using a CAsyncSocket Object to use CAsyncSocket
    473
  1. Find Files in certain directory
    935
  2. Implementing C#'s foreach loop in Delphi 8
    463
  3. How to detect resource leaks in a Form
    950
  4. The best way to enable and disable buttons, menu items and toolbar buttons
    668
  5. How to exit from a console application
    816
  6. How to restrict a program to a single instance
    732
  7. Compress and decompress strings in C#
    975
  8. Graphics in C# - Irregular Forms
    914
  9. Extracting the Country from IP Address
    471
  10. How to run shell command by MFC ?
    441
  11. Binary Search Sample Code
    409
  12. Double Linked List based in C++
    799
  13. String Replace Function For C#
    1,559
  14. How to print character in C# by ASCII code
    479
  15. MFC based World Wide Web HTTP Server Source Code
    462
  16. Using the shell to receive notification of removable media being inserted or removed
    681
  17. Adding Custom Paper Sizes To Named Printers
    651
  18. Print HTML In C# With Or Without The Web Browser Control And The Print Dialog
    972
  19. A Customizable Printing Text Class
    439
  20. Simplified .NET Printing In C#
    696
  21. How To Print Text In C#
    456
  22. C# Lists
    1,162
  23. Simple Example of IF/THEN using C#
    1,271
  24. Fast and Good Keyboard/Mouse Test without the message handler
    985
  25. Simple CGI Programming in C
    550
  26. C++ CGI Example working on Apache
    490
  27. Simple C# CGI working on Apache
    486
  28. How to send binary data through C# CGI app?
    998
  29. Interacting With TinyPic From C#
    1,314
  30. Creating A Watched Folder With Assigned Events
    1,672
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,906
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    672
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232