Click here to Skip to main content
6,631,889 members and growing! (23,349 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » MFC » General     Beginner License: The GNU General Public License (GPL)

Simple server client UDP Socket program

By buntyrolln

Simple MFC Application for Sending and Receiving UDP datagram
C++ (VC6), C++/CLI, Windows (WinXP, Win2003, Vista), MFC, Dev
Posted:5 Jun 2008
Views:19,956
Bookmarked:11 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
4 votes for this article.
Popularity: 1.93 Rating: 3.20 out of 5
1 vote, 25.0%
1

2

3
1 vote, 25.0%
4
2 votes, 50.0%
5

Introduction

This is a simple application demonstrating UDP client server in MFC.There are many examples related to TCP but very few for UDP. So,I thought of making simple application and uploading it
here.

Background

The main Dialog act as a server. Server will keep on waiting for data on a particular port, it receives the data and display. The client is started on clicking start button of main dialog. It can send data to server. Server receives the data and display it.

Using the code

The Main Dialog class CSimpleUDPDlg acts as a server. A thread is started in OnInitDialog() of man dialog to receive the data send by client.

Code snippet of CSimpleUDPDlg.cpp and CClientSend.cpp is shown below.

 #include "afxsock.h" 
//Add global variables 
    HANDLE thr;
    unsigned long id1; 
 // Definition of Thread ReceiveData shown below. 

UINT ReceiveData(LPVOID pParam)
{
    CSimpleUDPDlg *dlg=(CSimpleUDPDlg*)pParam;
    AfxSocketInit(NULL);
    CSocket echoServer;  

     // Create socket for sending/receiving datagrams
      if (echoServer.Create(514, SOCK_DGRAM, NULL)== 0) {
        AfxMessageBox("Create() failed");
      }

    for(;;) { // Run forever

    // Client address
    SOCKADDR_IN echoClntAddr; 

    // Set the size of the in-out parameter
    int clntAddrLen = sizeof(echoClntAddr);

    // Buffer for echo string
    char echoBuffer[ECHOMAX]; 
 
    // Block until receive message from a client
    int recvMsgSize = echoServer.ReceiveFrom(echoBuffer, 
      ECHOMAX, (SOCKADDR*)&echoClntAddr, &clntAddrLen, 0);
    if (recvMsgSize < 0) {
      AfxMessageBox("RecvFrom() failed");
    }

    
    echoBuffer[recvMsgSize]='\0';
    
    dlg->m_edit.ReplaceSel(echoBuffer);
    dlg->m_edit.ReplaceSel("\r\n");

   
  }


BOOL CSimpleUDPDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    // Add "About..." menu item to system menu.

    // IDM_ABOUTBOX must be in the system command range.
    ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
    ASSERT(IDM_ABOUTBOX < 0xF000);

    CMenu* pSysMenu = GetSystemMenu(FALSE);
    if (pSysMenu != NULL)
    {
        CString strAboutMenu;
        strAboutMenu.LoadString(IDS_ABOUTBOX);
        if (!strAboutMenu.IsEmpty())
        {
            pSysMenu->AppendMenu(MF_SEPARATOR);
            pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
        }
    }

    // Set the icon for this dialog.  The framework does this automatically
    //  when the application's main window is not a dialog
    SetIcon(m_hIcon, TRUE);            // Set big icon
    SetIcon(m_hIcon, FALSE);        // Set small icon

    //start a thread to receive data send by client 
    thr=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ReceiveData,this,NULL,&id1);
    // TODO: Add extra initialization here
    
    return TRUE;  // return TRUE  unless you set the focus to a control
}     
//The client dialog is started in OnStart() function  

void CSimpleUDPDlg::OnStart() 
{
    // TODO: Add your control notification handler code here
    CClientSend send;
    send.DoModal();
}


     
//Code Snippet of CClientSend.cpp is shown below which is a simple dialog class. 
#include "afxsock.h" 

void CClientSend::OnSend() 
{
    // TODO: Add your control notification handler code here
    AfxSocketInit( NULL);
    CString Buffer;
    m_editsend.GetWindowText(Buffer);
    int buflen=strlen(Buffer);

     CSocket echoClient;  

     if (echoClient.Create(0,SOCK_DGRAM,NULL) == 0) {
    AfxMessageBox("Create() failed");
    }
// in place of localhost we can give IP Address of the Particular machine.
     if (echoClient.SendTo(Buffer, buflen,514,
      (LPCSTR)"localhost", 0) != buflen) {
    AfxMessageBox("SendTo() sent a different number of bytes than expected");
  }

     echoClient.Close();

} 

Points of Interest

Well this is my first Article,hope it would be helpful.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPL)

About the Author

buntyrolln


Member
I am a software developer working with Visual C++.
Occupation: Software Developer
Location: India India

Other popular MFC articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
GeneralGood One PinmemberNyachhyon123453:34 22 Apr '09  
GeneralCode PinmemberXeifrank12:58 12 Jun '08  
AnswerRe: Code Pinmemberbuntyrolln19:52 12 Jun '08  
GeneralRe: Code PinmemberXeifrank8:33 16 Jun '08  
AnswerRe: Code Pinmemberbuntyrolln19:01 16 Jun '08  
GeneralRe: Code PinmemberMadhu_Rani0:05 24 Jul '09  
General.aspx wtf? Pinmember leppie 3:25 6 Jun '08  
GeneralRe: .aspx wtf? Pinmemberbuntyrolln4:21 6 Jun '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 5 Jun 2008
Editor:
Copyright 2008 by buntyrolln
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project