The following describes a simple sample of receiving UDP packets using CAsyncSocket.
Most of the code exists in a class derived from CAsyncSocket. Therefore begin
by using the ClassWizard to derive a class from CAsyncSocket. I used CUDPSocket
for my class name. Since CAsyncSocket is asynchronous, we must provide an event
handler for receiving. So add an override of OnReceive and modify it in a manner
as in the following:
void CUDPSocket::OnReceive(int nErrorCode) {
CUDPRecord UDPRecord;
CString Message;
char Buffer[512]; // Increase in size as needed
DWORD Error;
CAsyncSocket::OnReceive(nErrorCode);
if (nErrorCode) {
Message.Format("OnReceive nErrorCode: %i", nErrorCode);
AfxMessageBox(Message);
return;
}
UDPRecord.m_Size = ReceiveFrom(Buffer, sizeof Buffer, UDPRecord.m_IPAddress,
UDPRecord.m_Port);
if (!UDPRecord.m_Size || UDPRecord.m_Size == SOCKET_ERROR) {
Error = GetLastError();
Message.Format("ReceiveFrom error code: %u", Error);
AfxMessageBox(Message);
return;
}
// process the data
}
Note that I am using the following class to contain the packet information.
The following does not include the data. You do not need to use a class such as
this for the data and you can add a member or members for the data as needed
and/or remove unneeded members.
class CUDPRecord : public CObject {
DECLARE_DYNAMIC(CUDPRecord)
public:
CString m_IPAddress;
UINT m_Port;
int m_Size;
};
I also added a member function to simplify the creation of a socket, as in
the following:
void CUDPSocket::Create(UINT nSocketPort) {
CString Message;
DWORD Error;
if (CAsyncSocket::Create(nSocketPort, SOCK_DGRAM, FD_READ, "0.0.0.0"))
return;
Error = GetLastError();
Message.Format("The socket for port %u was not created; error %u",
nSocketPort, Error);
AfxMessageBox(Message);
}
Then to create the socket:
ListenSocket.Create(Port);
Where:
- ListenSocket
- is an instance of the class derived from CAsyncSocket (such as
CUDPSocket above)
- Port
- is the port to listen to
Be sure to close the socket as in:
ListenSocket.Close();
Initializing Windows Sockets
Call AfxSocketInit in your InitInstance to initialize Windows Sockets.