-
Notifications
You must be signed in to change notification settings - Fork 10
/
udpclient.h
117 lines (105 loc) · 1.87 KB
/
udpclient.h
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
110
111
112
113
114
115
116
117
#ifndef __UDPCLIENT_H__
#define __UDPCLIENT_H__
#ifdef _WIN32
#include <winsock2.h>
#endif
#include <stdio.h>
#include <thread>
#include <mutex>
#include "udptask.h"
template<typename T>
class udpclient
{
public:
udpclient() :utask(NULL){}
~udpclient()
{
if (utask != NULL)
{
delete utask;
}
}
bool connect(const char *addr, unsigned short int port, IUINT32 conv)
{
if (!udpsock.connect(addr, port))
{
return false;
}
utask = new T;
if (!utask->init(conv, &udpsock))
{
return false;
}
isstop = false;
_thread = std::thread(std::bind(&udpclient::run, this));
_threadtm = std::thread(std::bind(&udpclient::loop, this));
return true;
}
int send(const char *buf, int size)
{
_mutex.lock();
int ret = utask->send(buf, size);
_mutex.unlock();
return ret;
}
void shutdown()
{
isstop = true;
udpsock.shutdown();
_thread.join();
_threadtm.join();
}
void loop()
{
for (; !isstop;)
{
_mutex.lock();
utask->timerloop();
_mutex.unlock();
std::chrono::milliseconds dura(1);
std::this_thread::sleep_for(dura);
}
}
void run()
{
char buff[65536] = { 0 };
struct sockaddr_in seraddr;
for (; !isstop;)
{
socklen_t len = sizeof(struct sockaddr_in);
int size = udpsock.recvfrom(buff, sizeof(buff), (struct sockaddr*)&seraddr, &len);
if (size == 0)
{
continue;
}
if (size < 0)
{
printf("接收失败 %d,%d \n", udpsock.getsocket(), size);
continue;
}
_mutex.lock();
utask->recv(buff, size);
_mutex.unlock();
}
}
bool isalive()
{
_mutex.lock();
bool alive = utask->isalive();
_mutex.unlock();
return alive;
}
virtual int parsemsg(const char *buf, int len)
{
printf("收到数据 %s,%d\n", buf, len);
return 0;
}
private:
udpsocket udpsock;
udptask* utask;
std::thread _thread;
std::thread _threadtm;
std::mutex _mutex;
volatile bool isstop;
};
#endif