-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUDPServer.cpp
112 lines (82 loc) · 1.86 KB
/
UDPServer.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "UDPServer.h"
#include <stdio.h>
UDPServer::UDPServer()
{
}
UDPServer::~UDPServer()
{
}
void UDPServer::SetCallback(void *ptr)
{
server_call_back = (SERVER_CALLBACK)ptr;
}
DWORD WINAPI ServerThread (LPVOID parms)
{
int len;
UDPServer *srv = (UDPServer*)parms;
char recv_buf[2048];
int addr_len = sizeof(srv->addr);
while(srv->server_active)
{
len = recvfrom(srv->sock,
recv_buf,
2048,
0,
(SOCKADDR *)&(srv->addr),
&addr_len
);
if(len<=0)
break;
if(len > 0)
srv->server_call_back(recv_buf, len);
}
return 0;
}
int UDPServer::Open(int port)
{
int result = WSAStartup(MAKEWORD(2,2), &wsaData);
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_active = 0;
result = bind(sock, (SOCKADDR *) &addr, sizeof(addr));
if(result == 0)
{
hServerThread = CreateThread(NULL,
0,
ServerThread,
this, 0,
&ServerThreadID);
}
if (hServerThread == INVALID_HANDLE_VALUE)
{
result = -1;
}
if(sock == INVALID_SOCKET)
{
result = -1;
}
if(result == 0)
{
server_active = 1;
}
return result;
}
int UDPServer::Send(char *buf, int len)
{
int result = sendto(sock,
buf,
len,
0,
(SOCKADDR *) &addr,
sizeof(addr));
return result;
}
int UDPServer::Close(void)
{
server_active = 0;
int result = closesocket(sock);
WSACleanup();
return result;
}