-
Notifications
You must be signed in to change notification settings - Fork 28
/
listen_connect.cc
72 lines (55 loc) · 1.09 KB
/
listen_connect.cc
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
#include <mp/wavy.h>
#include <mp/functional.h>
#include <arpa/inet.h>
using namespace mp::placeholders;
void accepted(int fd, int err)
{
if(fd < 0) {
errno = err;
perror("accept error");
return;
}
try {
std::cout << "accepted" << std::endl;
// do something with fd
close(fd);
} catch (...) {
::close(fd);
return;
}
}
void connected(int fd, int err)
{
if(fd < 0) {
errno = err;
perror("connect error");
return;
}
try {
std::cout << "connected" << std::endl;
// do something with fd
} catch (...) { }
::close(fd);
}
int main(void)
{
mp::wavy::loop lo;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_port = htons(9090);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
lo.listen(PF_INET, SOCK_STREAM, 0,
(struct sockaddr*)&addr, sizeof(addr),
mp::bind(&accepted, _1, _2));
lo.start(4); // run with 4 threads
{
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
lo.connect(PF_INET, SOCK_STREAM, 0,
(struct sockaddr*)&addr, sizeof(addr),
0.0, connected);
}
usleep(50*1e3);
lo.end();
lo.join();
}