#include <winsock2.h> #define UM_READ_DATA (WM_USER + 1) #define BUFFERSIZE 512 #define PORT_NUMBER 10000 SOCKET g_udpSocket; BOOL InitSocket(HWND hWnd) { WSADATA wsaData; WSAStartup(MAKEWORD(2, 0), &wsaData); g_udpSocket = WSASocket(AF_INET, SOCK_DGRAM, 0, NULL, NULL, 0); SOCKADDR_IN addrIn; addrIn.sin_addr.S_un.S_addr = htonl(INADDR_ANY); addrIn.sin_family = AF_INET; addrIn.sin_port = htons(PORT_NUMBER); bind(g_udpSocket, (SOCKADDR*) &addrIn, sizeof(SOCKADDR)); WSAAsyncSelect(g_udpSocket, hWnd, UM_READ_DATA, FD_READ); return TRUE; } LRESULT OnReadData(WPARAM wParam, LPARAM lParam) { if (FD_READ == LOWORD(lParam)) { CHAR* szBuffer = new CHAR[BUFFERSIZE]; WSABUF wsabuf; wsabuf.buf = szBuffer; wsabuf.len = BUFFERSIZE; DWORD dwRecv; DWORD dwFlag; SOCKADDR_IN addrIn; int nLen = sizeof(SOCKADDR); WSARecvFrom(g_udpSocket, &wsabuf, 1, &dwRecv, &dwFlag, (SOCKADDR*) &addrIn, &nLen, NULL, NULL); UINT cbWstr = MultiByteToWideChar(CP_ACP, 0, wsabuf.buf, -1, NULL, 0); WCHAR* szWstr = new WCHAR[cbWstr]; MultiByteToWideChar(CP_ACP, 0, wsabuf.buf, -1, szWstr, cbWstr); delete szWstr; } return 0; } void OnSendData(DWORD dwHost, LPCWSTR lpszSend) { SOCKADDR_IN addrIn; addrIn.sin_addr.S_un.S_addr = htonl(dwHost); addrIn.sin_family = AF_INET; addrIn.sin_port = htons(PORT_NUMBER); UINT cbStr = WideCharToMultiByte(CP_ACP, 0, lpszSend, -1, NULL, 0, NULL, NULL); CHAR* szStr = new CHAR[cbStr]; WideCharToMultiByte(CP_ACP, 0, lpszSend, -1, szStr, cbStr, NULL, NULL); WSABUF wsabuf; wsabuf.buf = szStr; wsabuf.len = cbStr; DWORD dwSend; int nLen = sizeof(SOCKADDR); WSASendTo(g_udpSocket, &wsabuf, 1, &dwSend, 0, (SOCKADDR*) &addrIn, nLen, NULL, NULL); }