forked from jwcpp/jwEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest_Udp.cpp
More file actions
80 lines (64 loc) · 1.36 KB
/
Copy pathTest_Udp.cpp
File metadata and controls
80 lines (64 loc) · 1.36 KB
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
#include "KcpClient.h"
#include "KcpServer.h"
#include "EventLoop.h"
#include "KcpEvent.h"
#include "KcpSession.h"
#include "UdpPacket.h"
#include <time.h>
class KNetEvent : public KcpEvent
{
public:
virtual KcpSession * createConnect()
{
return new KcpSession(this, 1000);
}
virtual void onAccept(KcpSession * conn){
if (conn)
{
// 通知服务器有客户端连入
}
};
virtual void onConnect(KcpSession * conn){
if (conn)
{
// 通知客户端连接成功
int x = rand() % 100000;
std::string s(std::to_string(x));
conn->sendMsg(1, s.c_str(), s.length());
}
};
virtual void onClose(KcpSession * conn){
};
virtual void onMsg(KcpSession * conn, int msgtype, UdpPacket * pack){
std::string s;
(*pack) >> s;
printf("%s\n", s.c_str());
conn->sendMsg(1, pack);
}
virtual void onUdpTimeout(KcpSession * s)
{
printf("timeout ..............\n");
server->closeSession(s);
}
KcpServer * server;
};
//#define UDP_CLIENT_TEST
int main()
{
srand((int)time(0));
EventLoop::Instance()->init();
//初始化事件循环
KNetEvent eve;
EventLoop::Instance()->init();
#ifdef UDP_CLIENT_TEST
KcpClient client(EventLoop::Instance(), &eve);
client.createSession("127.0.0.1", 3001);
#else
KcpServer server(EventLoop::Instance(), &eve);
server.start("127.0.0.1", 3001);
eve.server = &server;
#endif
EventLoop::Instance()->run();
system("pause");
return 0;
}