一种低质量的网络连接方式。
服务器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
using namespace boost::asio::ip;
using namespace std;
const int MAX_LENGTH = 1024;
typedef std::shared_ptr<tcp::socket> socket_ptr;
std::set<std::shared_ptr<std::thread>> thread_set;
using namespace std;
void session(socket_ptr sock)
{
try
{
for (;;)
{
char data[MAX_LENGTH];
memset(data, '\0', MAX_LENGTH);
boost::system::error_code error;
//size_t length = boost::asio::read(sock, boost::asio::buffer(data, MAX_LENGTH), error);
size_t length = sock->read_some(boost::asio::buffer(data, MAX_LENGTH), error);
if (error == boost::asio::error::eof)
{
std::cout << "connection closed by peer" << endl;
break;
}
else if (error)
{
throw boost::system::system_error(error);
}
cout << "receive from " << sock->remote_endpoint().address().to_string() << endl;
cout << "receive message is " << data << endl;
//回传给对方
boost::asio::write(*sock, boost::asio::buffer(data, length));
}
}
catch (const std::exception& e)
{
std::cerr << "Exception in thread" << e.what() << "\n" << std::endl;
}
}
void server(boost::asio::io_context& io_context, unsigned short port)
{
tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port));
for (;;)
{
socket_ptr socket(new tcp::socket(io_context));
a.accept(*socket);
auto t = std::make_shared<std::thread>(session, socket);
thread_set.insert(t);//引用计数加一
}
}
int main()
{
try
{
boost::asio::io_context ioc;
server(ioc, 10086);
for (auto& t : thread_set)
{
t->join();//子线程全部退出之后主线程才退出
}
}
catch (const std::exception& e)
{
std::cerr << "Exception in thread" << e.what() << "\n" << std::endl;
}
return 0;
}
客户端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
using namespace boost::asio::ip;
using namespace std;
const int MAX_LENGTH = 1024;
int main()
{
try
{
//创建上下文服务
boost::asio::io_context ioc;
tcp::endpoint remote_ep(address::from_string("127.0.0.1"), 10086);
tcp::socket sock(ioc);
boost::system::error_code error = boost::asio::error::host_not_found;
sock.connect(remote_ep, error);
if (error)
{
cout << "connect failed,code is " << error.value() << "error msg is" << error.message();
return 0;
}
std::cout << "Enter message" << endl;
char request[MAX_LENGTH];
std::cin.getline(request, MAX_LENGTH);
size_t request_length = strlen(request);
boost::asio::write(sock, boost::asio::buffer(request, request_length));
char reply[MAX_LENGTH];
size_t reply_length = boost::asio::read(sock, boost::asio::buffer(reply, request_length));
std::cout << "Reply is :";
std::cout.write(reply, reply_length);
std::cout << "\n";
}
catch (const std::exception& e)
{
std::cerr << "Exception:" << e.what() << endl;
}
}