-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathudpserver.cpp
75 lines (57 loc) · 1.51 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
#include "udpserver.h"
bool CUdpServer::Start(unsigned long IP, unsigned short Port)
{
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(Port);
addr.sin_addr.s_addr = htonl(IP);
m_Socket = socket(PF_INET, SOCK_DGRAM, 0);
fcntl(m_Socket, F_SETFL, fcntl(m_Socket, F_GETFL) | O_NONBLOCK);
if (bind(m_Socket, (struct sockaddr *)&addr, sizeof(addr)) != 0)
{
// bind error
return false;
}
m_Io.set(m_Loop);
m_Io.set<CUdpServer, &CUdpServer::__ReadCallback>(this);
m_Io.start(m_Socket, ev::READ);
m_Loop.loop();
return true;
}
bool CUdpServer::Stop()
{
if (m_Socket > 0)
{
close(m_Socket);
m_Socket = 0;
}
m_Io.stop();
m_Loop.unloop();
return true;
}
void CUdpServer::Send(unsigned long IP, unsigned short Port, const char * pData, int nDataLen)
{
if (m_Socket > 0)
{
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(Port);
addr.sin_addr.s_addr = htonl(IP);
sendto(m_Socket, pData, nDataLen, 0, (sockaddr*)&addr, sizeof(struct sockaddr_in));
}
}
void CUdpServer::__ReadCallback(ev::io &watcher, int revents)
{
if (EV_ERROR & revents)
{
return;
}
char szBuffer[1500];
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
ssize_t nRead = recvfrom(watcher.fd, szBuffer, sizeof(szBuffer), 0, (sockaddr*)&addr, &addrlen);
if (nRead > 0)
{
m_pDataHandle->OnDataReceived(ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port ), szBuffer, nRead);
}
}