用Asio实现同步echo服务器

news/2024/9/23 18:33:27

使用Asio实现同步echo服务器

服务端

sync_server.h

#ifndef  ASYNC_SERVER_H
#define	 ASYNC_SERVER_H
#include <boost/asio/ip/tcp.hpp>
#include <memory>
#include <set>
#include <thread>namespace MS {typedef std::shared_ptr<boost::asio::ip::tcp::socket> socket_ptr;class AsyncServer {public:AsyncServer(unsigned short);~AsyncServer() {}void listen();void session(socket_ptr);private:unsigned short _port;boost::asio::ip::tcp::acceptor _acceptor;std::set<std::shared_ptr<std::thread>> _connect_thread; private:void read_message();void send_message();};
}
#endif // ! ASYNC_SERVER_H

sync_client.cpp

#include <iostream>
#include <string>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>#include "async_server.h"
boost::asio::io_context IOC;
namespace MS {using namespace std;using namespace boost::asio;#define MAX_SZIE 1024AsyncServer::AsyncServer(unsigned short port):_port{port}, _acceptor{IOC, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), _port)}{std::cout << "the server initing." << std::endl;this->listen();std::cout << "the server is running." << std::endl;}void AsyncServer::listen() {while(1) {std::cout << "listen the connection...\n";socket_ptr sock_{new ip::tcp::socket(IOC)};this->_acceptor.accept(*sock_);std::cout << "new connection from " << sock_->remote_endpoint().address() << std::endl;char data[MAX_SZIE];boost::system::error_code ec;memset(data, '\0', MAX_SZIE);sock_->async_read_some(boost::asio::buffer(data, MAX_SZIE), ec);if (ec.value() != 0) {std::cerr << "the async read is falie: " << ec.value() << " message: " << ec.message() << std::endl;}cout.write(data, MAX_SZIE);sock_->async_write_some(boost::asio::buffer(data, MAX_SZIE),ec);if (ec.value() != 0) {std::cerr << "the async send is falie: " << ec.value()<< " message: " << ec.message() << std::endl;}//std::thread session_thread(MS::AsyncServer::session, this, sock_);/*std::thread session_thread([&]() {this->session(sock_);});*///session_thread.join();//delete session_thread;}}void AsyncServer::session(socket_ptr socket) {for(;;){try{char data[MAX_SZIE];memset(data, '\0', MAX_SZIE);boost::system::error_code error;size_t send_length = socket->read_some(boost::asio::buffer(data, MAX_SZIE), error);if(error.value() != 0){cerr << "read message error,code is " << error.value() << ", message is " << error.message() << endl;return;}cout << "write message's length is : " << send_length << endl;cout.write(data, MAX_SZIE);socket->write_some(boost::asio::buffer(data), error);if(error.value() != 0){cerr << "write message error: " << error.message() << endl;}} catch(...){cout << "Client disconnected" << endl;}}	}void AsyncServer::send_message() {}void AsyncServer::read_message() {}
}int main() {try{IOC.run();MS::AsyncServer server(10086);} catch(std::exception &e){std::cerr << "Exception: " << e.what() << std::endl;}
}

客户端

sync_client.h

#pragma once#include <iostream>
#include <boost/asio/ip/tcp.hpp>namespace MC {class Client {public:Client(const std::string&, unsigned short);void connect_to_server();void runClient();void send_message();void receive_message();private:boost::asio::ip::tcp::socket _sock;boost::asio::ip::tcp::endpoint _remote_endpoint;	};
}

sync_client.cpp


#include <iostream>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>#include "async_client.h"static boost::asio::io_context IOC;
namespace MC {using namespace std;using namespace boost::asio::ip;#define MAX_LENGTH 1024Client::Client(const std::string& host, unsigned short port):_sock{IOC}, _remote_endpoint{ address::from_string(host), port }{this->connect_to_server();this->runClient();}// connect to the server by host and portvoid Client::connect_to_server() {try {boost::system::error_code ec = boost::asio::error::host_not_found;_sock.connect(_remote_endpoint, ec);if(ec.value() != 0) {std::cout << "connect failed, code is " << ec.value() << " error msg is " << ec.message() << std::endl;return;}std::cout << "connect success!" << std::endl;}catch(...) {std::cout << "connect failed! system error." << std::endl;}}// run the clientvoid Client::runClient(){while(true) {this->send_message();this->receive_message();}}// send message to servervoid Client::send_message() {try {std::string msg;std::cout << "Enter message: ";std::getline(std::cin, msg);boost::asio::write(_sock, boost::asio::buffer(msg));}catch(...) {std::cout << "send message failed! system error." << std::endl;}}void Client::receive_message() {try {char reply[MAX_LENGTH];size_t reply_length = boost::asio::read(_sock,boost::asio::buffer(reply, MAX_LENGTH));std::cout << "Reply is: ";std::cout.write(reply, reply_length);std::cout << "\n";}catch(...) {std::cout << "receive message failed! system error." << std::endl;}}}int main() {MC::Client client("127.0.0.1", 10086);// client.runClient();
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ryyt.cn/news/63863.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

java如何调用外部程序

java如何调用外部程序 2017-03-15 20:50 179人阅读 评论(0) 收藏 举报 分类:Java应用(26) 版权声明:本文为博主原创文章,未经博主允许不得转载。引言;有时候有些项目需求,直接使用Java编写比较麻烦,所有我们可能使用其他语言编写的程序来实现。那么我们如何在java中调…

高级程序语言设计课程第一次个人作业

这个作业属于的课程:https://edu.cnblogs.com/campus/fzu/2024C 作业要求:https://edu.cnblogs.com/campus/fzu/2024C 学号:102400213 姓名:范自亮 安装过程及成功画面:作业内容: 2.12.22.3问题:输出的语句连在一起未分行 解决方案:询问老师后自行修改 总结与思考:理论…

Javascript调试命令——你只会Console.log() ?

Javascript调试命令——你只会Console.log() ? https://segmentfault.com/a/1190000012957199 Console 对象提供对浏览器控制台的接入(如:Firefox 的 Web Console)。不同浏览器上它的工作方式是不一样的,但这里会介绍一些大都会提供的接口特性。Console对象可以在任何全局…

ES毛刺问题

es 毛刺问题 在写入时,边写边查并不会出现明显毛刺,但在写入时不查询,写入完成后再查询会出现明显毛刺。下图的三个毛刺是在是用反转索引时,写入完成后切换索引时出现。通过 remove 和 add 别名可以无感切换索引 /_aliases {"actions": [{"add": {&quo…

『模拟赛』CSP-S模拟3

『模拟赛记录』CSP-S模拟3因为正式集训所以不叫加赛了。Rank Upd:非常好 数据,掉分掉 Rank。 还行,其实是 Rank6,其实其实是 Rank4(丁真说正式比赛不会改数据。A. 奇观 简单题(?)。 赛时琢磨了一会想到了 \(Ans=C\cdot C\cdot F\),打出了 \(m=0\) 性质和 \(O(n^2)\) d…

Spark(七)Spark运行架构

运行架构Spark框架的核心是一个计算引擎,采用了标准master-slave的结构 如图展示了一个Spark执行时的基本结构,Driver表示master,负责管理整个集群中的作业任务调度,Executor是slave,负责实际执行任务核心组件 1. DriverSpark驱动器节点,用于执行Spark任务中的main方法,…

Go进阶01:golang context 上下文用法详解(比较好理解)

1 前言最近实现系统的分布式日志与事务管理时,在寻求所谓的全局唯一Goroutine ID无果之后,决定还是简单利用Context机制实现了基本的想法,不够高明,但是好用.于是对它当初的设计比较好奇,便有了此文.Context是golang官方定义的一个package,它定义了Context类型,里面包含了Deadl…