public
Last active

  • Download Gist
UdpSocket.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#include "stdafx.h"
 
#include <stdio.h>
#include <WinSock2.h>
 
#include <iostream>
#include <string>
using namespace std;
 
class UDPSocket {
int m_bufferSize;
WSAData m_wsaData;
SOCKET m_sock;
struct sockaddr_in m_addr;
 
public:
UDPSocket(u_short port, int bufferSize = 1024)
{
m_bufferSize = bufferSize;
 
// Initialize winsock and create socket
WSAStartup(MAKEWORD(2, 0), &m_wsaData);
m_sock = socket(AF_INET, SOCK_DGRAM, 0);
 
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.S_un.S_addr = INADDR_ANY;
 
::bind(m_sock, (struct sockaddr *)&addr, sizeof(addr));
}
 
~UDPSocket()
{
// close socket & cleanup
closesocket(m_sock);
WSACleanup();
}
 
string recv()
{
string result;
 
char *buf = new char[m_bufferSize + 1];
memset(buf, 0, m_bufferSize + 1);
::recv(m_sock, buf, m_bufferSize, 0);
 
result = string(buf);
delete buf;
 
return result;
}
};
 
 
int _tmain(int argc, _TCHAR* argv[])
{
UDPSocket udp(12345); // bind port 12345
string buf;
do {
buf = udp.recv();
cout << buf;
} while(buf != "end\n");
 
//cout << "--- Press any key to exit ---" << endl;
//getc(stdin);
 
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.