-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathSample.AsyncSocket.h
94 lines (77 loc) · 2.29 KB
/
Sample.AsyncSocket.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
#pragma once
// https://github.com/vic4key/async-socket-example
#include "Sample.h"
#if defined(VU_INET_ENABLED)
void example_binding(const vu::Endpoint& endpoint)
{
vu::AsyncSocket server;
server.on(vu::AsyncSocket::OPEN, [](vu::Socket& client) -> void
{
printf("\n");
printf("client %d opened\n", client.get_remote_sai().sin_port);
});
server.on(vu::AsyncSocket::CLOSE, [](vu::Socket& client) -> void
{
printf("client %d closed\n", client.get_remote_sai().sin_port);
});
//server.on(vu::AsyncSocket::SEND, [](vu::Socket& client) -> void
//{
// std::string s = "hello from server";
// client.send(s.data(), int(s.size()));
// printf("client %d send `%s`\n", client.get_remote_sai().sin_port, s.c_str());
//});
server.on(vu::AsyncSocket::RECV, [](vu::Socket& client) -> void
{
vu::Buffer data(KiB);
client.recv(data);
printf("client %d recv `%s`\n", client.get_remote_sai().sin_port, data.as_string_A()->c_str());
});
server.bind(endpoint);
server.listen();
server.run();
// server.stop();
}
void example_inheritance(const vu::Endpoint& endpoint)
{
class CAsyncSocketServer : public vu::AsyncSocket
{
public:
virtual void on_open(vu::Socket& client)
{
printf("\n");
printf("client %d opened\n", client.get_remote_sai().sin_port);
}
virtual void on_close(vu::Socket& client)
{
printf("client %d closed\n", client.get_remote_sai().sin_port);
}
//virtual void on_send(vu::Socket& client)
//{
// std::string s = "hello from server";
// client.send(s.data(), int(s.size()));
// printf("client %d send `%s`\n", client.get_remote_sai().sin_port, s.c_str());
//}
virtual void on_recv(vu::Socket& client)
{
vu::Buffer data(KiB);
client.recv(data);
std::string s(reinterpret_cast<char*>(data.bytes()));
printf("client %d recv `%s`\n", client.get_remote_sai().sin_port, s.c_str());
}
};
CAsyncSocketServer server;
server.bind(endpoint);
server.listen();
server.run();
// server.stop();
}
#endif // VU_INET_ENABLED
DEF_SAMPLE(AsyncSocket)
{
#if defined(VU_INET_ENABLED)
// const vu::Socket::sEndPoint endpoint("127.0.0.1", 1609);
// example_binding(endpoint);
// example_inheritance(endpoint);
#endif // VU_INET_ENABLED
return vu::VU_OK;
}