Skip to content

@snaka /UdpSocket.cpp
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.