Client Server communication using CAsyncSocket in UDP transmission.

Note:

m_sockServer is instance of class type  CServerSocket, which is derived class from CAsyncSocket. In CServerSocket, only one function has been overridden is OnReceive(). Nothing more than this.

Follow the below steps for Client Server communication using UDP.

1. Starting up the UDP server

m_uiPort = 5274;

if(m_sockServer.Create(m_uiPort, SOCK_DGRAM, FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE) == FALSE)
{
CString sMsg;
GetErrorMessage(GetLastError(), sMsg);
MessageBox(sMsg);
return;
}
2. Sending UDP data  to Server

int iReturn;
CAsyncSocket sockClient;
if(sockClient.Create(0, SOCK_DGRAM, FD_READ | FD_WRITE | FD_CLOSE) == FALSE)
{
CString sMsg;
GetErrorMessage(GetLastError(), sMsg);
MessageBox(sMsg);
return;
}

iReturn = sockClient.SendTo(LPCTSTR(m_sClientEditText), m_sClientEditText.GetLength(), m_uiPort, _T(“192.168.2.32”));//, , sizeof(sockAddr), 0);

if(iReturn == SOCKET_ERROR)
{
CString sMsg;
UINT Error = GetLastError();
GetErrorMessage(Error, sMsg);
MessageBox(sMsg);
return;
}

3. Receiving data that has sent in step 2,

void CServerSocket::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class

stClientData stClientIP;
static TCHAR lpszData[1024];
CString sClientIP, sMsg;
UINT uiPortNo;
int iSize;

CAsyncSocket::OnReceive(nErrorCode);
if (nErrorCode)
{
GetErrorMessage(nErrorCode, sMsg);
AfxMessageBox(sMsg);
return;
}

iSize = ReceiveFrom(lpszData, sizeof(lpszData), sClientIP, uiPortNo);

if (!iSize || iSize == SOCKET_ERROR)
{
UINT Error = GetLastError();
GetErrorMessage(Error, sMsg);
AfxMessageBox(sMsg);
return;
}

lpszData[iSize] = 0;

sMsg.Format(_T(“%s : %u : \”%s\””), sClientIP, uiPortNo, lpszData);

AfxMessageBox(sMsg);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: