forked from yyzybb537/libgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample5_asio.cpp
More file actions
64 lines (54 loc) · 1.57 KB
/
Copy pathsample5_asio.cpp
File metadata and controls
64 lines (54 loc) · 1.57 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
/************************************************
* libgo sample5
*************************************************/
/***********************************************
* 结合boost.asio, 使网络编程变得更加简单.
* 如果你不喜欢boost.asio, 这个例子可以跳过不看.
************************************************/
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include "coroutine.h"
#include "win_exit.h"
static const uint16_t port = 43332;
using namespace boost::asio;
using namespace boost::asio::ip;
using boost::system::error_code;
io_service ios;
tcp::endpoint addr(address::from_string("127.0.0.1"), port);
void echo_server()
{
tcp::acceptor acc(ios, addr, true);
for (int i = 0; i < 2; ++i) {
std::shared_ptr<tcp::socket> s(new tcp::socket(ios));
acc.accept(*s);
go [s]{
char buf[1024];
auto n = s->read_some(buffer(buf));
n = s->write_some(buffer(buf, n));
error_code ignore_ec;
n = s->read_some(buffer(buf, 1), ignore_ec);
};
}
}
void client()
{
tcp::socket s(ios);
s.connect(addr);
std::string msg = "1234";
int n = s.write_some(buffer(msg));
printf("client send msg [%d] %s\n", (int)msg.size(), msg.c_str());
char buf[12];
n = s.receive(buffer(buf, n));
printf("client recv msg [%d] %.*s\n", n, n, buf);
}
int main()
{
go echo_server;
go client;
go client;
// 200ms后安全退出
std::thread([]{ co_sleep(200); co_sched.Stop(); }).detach();
// 单线程执行
co_sched.Start();
return 0;
}