当前位置: 首页 > news >正文

Boost 网络库

asio

  • 网络编程的基本流程
  • 创建 socket
  • 绑定acceptor
  • 连接指定的端点
  • 服务器接受连接

网络编程的基本流程

  • 服务端

1)socket----创建socket对象。

2)bind----绑定本机ip+port。

3)listen----监听来电,若在监听到来电,则建立起连接。

4)accept----再创建一个socket对象给其收发消息。原因是现实中服务端都是面对多个客户端,那么为了区分各个客户端,则每个客户端都需再分配一个socket对象进行收发消息。

5)read、write----收发消息

  • 客户端

1)socket----创建socket对象。

2)connect----根据服务端ip+port,发起连接请求。

3)write、read----建立连接后,就可发收消息了

创建 socket

创建socket分为4步,创建上下文iocontext,选择协议,生成socket,打开socket。

int create_tcp_socket() {// Step 1. An instance of 'io_service' class is required by// socket constructor. asio::io_context  ios;// Step 2. Creating an object of 'tcp' class representing// a TCP protocol with IPv4 as underlying protocol.asio::ip::tcp protocol = asio::ip::tcp::v4();// Step 3. Instantiating an active TCP socket object.asio::ip::tcp::socket sock(ios);// Used to store information about error that happens// while opening the socket.boost::system::error_code ec;// Step 4. Opening the socket.sock.open(protocol, ec);if (ec.value() != 0) {// Failed to open the socket.std::cout<< "Failed to open the socket! Error code = "<< ec.value() << ". Message: " << ec.message();return ec.value();}return 0;
}

上述socket只是通信的socket,如果是服务端,我们还需要生成一个acceptor的socket,用来接收新的连接。

int  create_acceptor_socket() {// Step 1. An instance of 'io_service' class is required by// socket constructor. asio::io_context ios;// Step 2. Creating an object of 'tcp' class representing// a TCP protocol with IPv6 as underlying protocol.asio::ip::tcp protocol = asio::ip::tcp::v6();// Step 3. Instantiating an acceptor socket object.asio::ip::tcp::acceptor acceptor(ios);// Used to store information about error that happens// while opening the acceptor socket.boost::system::error_code ec;// Step 4. Opening the acceptor socket.acceptor.open(protocol, ec);if (ec.value() != 0) {// Failed to open the socket.std::cout<< "Failed to open the acceptor socket!"<< "Error code = "<< ec.value() << ". Message: " << ec.message();return ec.value();}return 0;
}

绑定acceptor

对于acceptor类型的socket,服务器要将其绑定到指定的端口,所有连接这个端口的连接都可以被接收到。

int  bind_acceptor_socket() {// Step 1. Here we assume that the server application has// already obtained the protocol port number.unsigned short port_num = 3333;// Step 2. Creating an endpoint.asio::ip::tcp::endpoint ep(asio::ip::address_v4::any(),port_num);// Used by 'acceptor' class constructor.asio::io_context  ios;// Step 3. Creating and opening an acceptor socket.asio::ip::tcp::acceptor acceptor(ios, ep.protocol());boost::system::error_code ec;// Step 4. Binding the acceptor socket.acceptor.bind(ep, ec);// Handling errors if any.if (ec.value() != 0) {// Failed to bind the acceptor socket. Breaking// execution.std::cout << "Failed to bind the acceptor socket."<< "Error code = " << ec.value() << ". Message: "<< ec.message();return ec.value();}return 0;
}

连接指定的端点

作为客户端可以连接服务器指定的端点进行连接

int  connect_to_end() {// Step 1. Assume that the client application has already// obtained the IP address and protocol port number of the// target server.std::string raw_ip_address = "127.0.0.1";unsigned short port_num = 3333;try {// Step 2. Creating an endpoint designating // a target server application.asio::ip::tcp::endpointep(asio::ip::address::from_string(raw_ip_address),port_num);asio::io_context ios;// Step 3. Creating and opening a socket.asio::ip::tcp::socket sock(ios, ep.protocol());// Step 4. Connecting a socket.sock.connect(ep);// At this point socket 'sock' is connected to // the server application and can be used// to send data to or receive data from it.}// Overloads of asio::ip::address::from_string() and // asio::ip::tcp::socket::connect() used here throw// exceptions in case of error condition.catch (system::system_error& e) {std::cout << "Error occured! Error code = " << e.code()<< ". Message: " << e.what();return e.code().value();}
}

服务器接受连接

int accept_new_connection(){// The size of the queue containing the pending connection// requests.const int BACKLOG_SIZE = 30;// Step 1. Here we assume that the server application has// already obtained the protocol port number.unsigned short port_num = 3333;// Step 2. Creating a server endpoint.asio::ip::tcp::endpoint ep(asio::ip::address_v4::any(),port_num);asio::io_context  ios;try {// Step 3. Instantiating and opening an acceptor socket.asio::ip::tcp::acceptor acceptor(ios, ep.protocol());// Step 4. Binding the acceptor socket to the // server endpint.acceptor.bind(ep);// Step 5. Starting to listen for incoming connection// requests.acceptor.listen(BACKLOG_SIZE);// Step 6. Creating an active socket.asio::ip::tcp::socket sock(ios);// Step 7. Processing the next connection request and // connecting the active socket to the client.acceptor.accept(sock);// At this point 'sock' socket is connected to //the client application and can be used to send data to// or receive data from it.}catch (system::system_error& e) {std::cout << "Error occured! Error code = " << e.code()<< ". Message: " << e.what();return e.code().value();}
}

相关文章:

  • 【植物大战僵尸杂交版】最新版2.1下载链接
  • 线程池的艺术:深度解析Java多线程并发性能的优化之道
  • 【AIGC】MetaGPT原理以及应用
  • 创建activity中的context
  • 什么是SLA
  • SAP-ABAP-03-课上代码
  • 【车载开发系列】汽车嵌入式开发常用工具介绍
  • 功能测试 之 单模块测试----抢购模块
  • [BFS广搜]迷阵
  • Android 一个改善的okHttp封装库
  • 第十一章:接口
  • Linux C编译器从零开发三
  • 02-ES6新语法
  • shell 三剑客-grep
  • SpringSecurity-入门代码
  • 【5+】跨webview多页面 触发事件(二)
  • Android组件 - 收藏集 - 掘金
  • Angular Elements 及其运作原理
  • iOS帅气加载动画、通知视图、红包助手、引导页、导航栏、朋友圈、小游戏等效果源码...
  • Java知识点总结(JDBC-连接步骤及CRUD)
  • jQuery(一)
  • js对象的深浅拷贝
  • laravel5.5 视图共享数据
  • MQ框架的比较
  • PHP 7 修改了什么呢 -- 2
  • Sass Day-01
  • seaborn 安装成功 + ImportError: DLL load failed: 找不到指定的模块 问题解决
  • Vue全家桶实现一个Web App
  • 京东美团研发面经
  • 排序算法之--选择排序
  • 前端面试之CSS3新特性
  • 译自由幺半群
  • 新年再起“裁员潮”,“钢铁侠”马斯克要一举裁掉SpaceX 600余名员工 ...
  • ​比特币大跌的 2 个原因
  • #QT(TCP网络编程-服务端)
  • #宝哥教你#查看jquery绑定的事件函数
  • #数据结构 笔记三
  • (16)UiBot:智能化软件机器人(以头歌抓取课程数据为例)
  • (7)摄像机和云台
  • (C++)八皇后问题
  • (M)unity2D敌人的创建、人物属性设置,遇敌掉血
  • (附源码)SSM环卫人员管理平台 计算机毕设36412
  • (回溯) LeetCode 40. 组合总和II
  • (七)glDrawArry绘制
  • (十五)、把自己的镜像推送到 DockerHub
  • (原創) 如何優化ThinkPad X61開機速度? (NB) (ThinkPad) (X61) (OS) (Windows)
  • .NET Compact Framework 3.5 支持 WCF 的子集
  • .Net mvc总结
  • .NET Standard 支持的 .NET Framework 和 .NET Core
  • .Net8 Blazor 尝鲜
  • .net反混淆脱壳工具de4dot的使用
  • .NET建议使用的大小写命名原则
  • .net生成的类,跨工程调用显示注释
  • .pyc文件还原.py文件_Python什么情况下会生成pyc文件?
  • .sh 的运行