简介
本文将使用官方的实例代码,编写一个自动交互的EchoServer。
N个客户端角色每过一秒向服务器发送一条字符串消息
服务器将接收到的消息,原封不动的返回给客户端,并在控制台输出是哪个客户端发送的什么消息
EchoExamples
服务器和客户端写死的都是5000端口
AsioEchoServer源码
//
// async_tcp_echo_server.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <memory>
#include <utility>
#include <asio.hpp>
#include <string.h>
using namespace std;
using asio::ip::tcp;
class session
: public std::enable_shared_from_this<session>
{
public:
session(tcp::socket socket)
: socket_(std::move(socket))
{
}
void start()
{
do_read();
}
private:
vo

本文介绍如何使用Asio库在C++中创建一个EchoServer,该服务器接收客户端发送的字符串并原样返回。示例代码展示了一个多客户端交互的场景,客户端每隔一秒钟发送消息,服务器在控制台上显示发送者和消息内容。
最低0.47元/天 解锁文章
378





