boost::asio之socket的创建和连接

网络编程基本流程

网络编程的基本流程对于服务端是这样的
服务端
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——建立连接后,就可发收消息了。

图示如下
https://cdn.llfc.club/1540562-20190417002428451-62583604.jpg
相关的网络编程技术可以看看我之前写的文章
https://llfc.club/category?catid=2LUTCbqG3H8TjiCTLIa2BcKIbHp#!aid/2LUgc9QwOBI43XPtWVYw0SznR4N
接下来按照上述流程,我们用boost::asio逐步介绍。

终端节点的创建

所谓终端节点就是用来通信的端对端的节点,可以通过ip地址和端口构造,其的节点可以连接这个终端节点做通信.
如果我们是客户端,我们可以通过对端的ip和端口构造一个endpoint,用这个endpoint和其通信。

  1. int client_end_point() {
  2. // Step 1. Assume that the client application has already
  3. // obtained the IP-address and the protocol port number.
  4. std::string raw_ip_address = "127.0.0.1";
  5. unsigned short port_num = 3333;
  6. // Used to store information about error that happens
  7. // while parsing the raw IP-address.
  8. boost::system::error_code ec;
  9. // Step 2. Using IP protocol version independent address
  10. // representation.
  11. asio::ip::address ip_address =
  12. asio::ip::address::from_string(raw_ip_address, ec);
  13. if (ec.value() != 0) {
  14. // Provided IP address is invalid. Breaking execution.
  15. std::cout
  16. << "Failed to parse the IP address. Error code = "
  17. << ec.value() << ". Message: " << ec.message();
  18. return ec.value();
  19. }
  20. // Step 3.
  21. asio::ip::tcp::endpoint ep(ip_address, port_num);
  22. // Step 4. The endpoint is ready and can be used to specify a
  23. // particular server in the network the client wants to
  24. // communicate with.
  25. return 0;
  26. }

如果是服务端,则只需根据本地地址绑定就可以生成endpoint

  1. int server_end_point(){
  2. // Step 1. Here we assume that the server application has
  3. //already obtained the protocol port number.
  4. unsigned short port_num = 3333;
  5. // Step 2. Create special object of asio::ip::address class
  6. // that specifies all IP-addresses available on the host. Note
  7. // that here we assume that server works over IPv6 protocol.
  8. asio::ip::address ip_address = asio::ip::address_v6::any();
  9. // Step 3.
  10. asio::ip::tcp::endpoint ep(ip_address, port_num);
  11. // Step 4. The endpoint is created and can be used to
  12. // specify the IP addresses and a port number on which
  13. // the server application wants to listen for incoming
  14. // connections.
  15. return 0;
  16. }

创建socket

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

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

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

  1. int create_acceptor_socket() {
  2. // Step 1. An instance of 'io_service' class is required by
  3. // socket constructor.
  4. asio::io_context ios;
  5. // Step 2. Creating an object of 'tcp' class representing
  6. // a TCP protocol with IPv6 as underlying protocol.
  7. asio::ip::tcp protocol = asio::ip::tcp::v6();
  8. // Step 3. Instantiating an acceptor socket object.
  9. asio::ip::tcp::acceptor acceptor(ios);
  10. // Used to store information about error that happens
  11. // while opening the acceptor socket.
  12. boost::system::error_code ec;
  13. // Step 4. Opening the acceptor socket.
  14. acceptor.open(protocol, ec);
  15. if (ec.value() != 0) {
  16. // Failed to open the socket.
  17. std::cout
  18. << "Failed to open the acceptor socket!"
  19. << "Error code = "
  20. << ec.value() << ". Message: " << ec.message();
  21. return ec.value();
  22. }
  23. return 0;
  24. }

绑定acceptor

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

  1. int bind_acceptor_socket() {
  2. // Step 1. Here we assume that the server application has
  3. // already obtained the protocol port number.
  4. unsigned short port_num = 3333;
  5. // Step 2. Creating an endpoint.
  6. asio::ip::tcp::endpoint ep(asio::ip::address_v4::any(),
  7. port_num);
  8. // Used by 'acceptor' class constructor.
  9. asio::io_context ios;
  10. // Step 3. Creating and opening an acceptor socket.
  11. asio::ip::tcp::acceptor acceptor(ios, ep.protocol());
  12. boost::system::error_code ec;
  13. // Step 4. Binding the acceptor socket.
  14. acceptor.bind(ep, ec);
  15. // Handling errors if any.
  16. if (ec.value() != 0) {
  17. // Failed to bind the acceptor socket. Breaking
  18. // execution.
  19. std::cout << "Failed to bind the acceptor socket."
  20. << "Error code = " << ec.value() << ". Message: "
  21. << ec.message();
  22. return ec.value();
  23. }
  24. return 0;
  25. }

连接指定的端点

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

  1. int connect_to_end() {
  2. // Step 1. Assume that the client application has already
  3. // obtained the IP address and protocol port number of the
  4. // target server.
  5. std::string raw_ip_address = "127.0.0.1";
  6. unsigned short port_num = 3333;
  7. try {
  8. // Step 2. Creating an endpoint designating
  9. // a target server application.
  10. asio::ip::tcp::endpoint
  11. ep(asio::ip::address::from_string(raw_ip_address),
  12. port_num);
  13. asio::io_context ios;
  14. // Step 3. Creating and opening a socket.
  15. asio::ip::tcp::socket sock(ios, ep.protocol());
  16. // Step 4. Connecting a socket.
  17. sock.connect(ep);
  18. // At this point socket 'sock' is connected to
  19. // the server application and can be used
  20. // to send data to or receive data from it.
  21. }
  22. // Overloads of asio::ip::address::from_string() and
  23. // asio::ip::tcp::socket::connect() used here throw
  24. // exceptions in case of error condition.
  25. catch (system::system_error& e) {
  26. std::cout << "Error occured! Error code = " << e.code()
  27. << ". Message: " << e.what();
  28. return e.code().value();
  29. }
  30. }

服务器接收连接

当有客户端连接时,服务器需要接收连接

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

关于buffer

任何网络库都有提供buffer的数据结构,所谓buffer就是接收和发送数据时缓存数据的结构。
boost::asio提供了asio::mutable_buffer 和 asio::const_buffer这两个结构,他们是一段连续的空间,首字节存储了后续数据的长度。
asio::mutable_buffer用于写服务,asio::const_buffer用于读服务。但是这两个结构都没有被asio的api直接使用。
对于api的buffer参数,asio提出了MutableBufferSequence和ConstBufferSequence概念,他们是由多个asio::mutable_buffer和asio::const_buffer组成的。也就是说boost::asio为了节省空间,将一部分连续的空间组合起来,作为参数交给api使用。
我们可以理解为MutableBufferSequence的数据结构为std::vector<asio::mutable_buffer>
结构如下
https://cdn.llfc.club/1676257797218.jpg
每隔vector存储的都是mutable_buffer的地址,每个mutable_buffer的第一个字节表示数据的长度,后面跟着数据内容。
这么复杂的结构交给用户使用并不合适,所以asio提出了buffer()函数,该函数接收多种形式的字节流,该函数返回asio::mutable_buffers_1 o或者asio::const_buffers_1结构的对象。
如果传递给buffer()的参数是一个只读类型,则函数返回asio::const_buffers_1 类型对象。
如果传递给buffer()的参数是一个可写类型,则返回asio::mutable_buffers_1 类型对象。
asio::const_buffers_1和asio::mutable_buffers_1是asio::mutable_buffer和asio::const_buffer的适配器,提供了符合MutableBufferSequence和ConstBufferSequence概念的接口,所以他们可以作为boost::asio的api函数的参数使用。
简单概括一下,我们可以用buffer()函数生成我们要用的缓存存储数据。
比如boost的发送接口send要求的参数为ConstBufferSequence类型

  1. template<typename ConstBufferSequence>
  2. std::size_t send(const ConstBufferSequence & buffers);

我们需要将”Hello Word转化为该类型”

  1. void use_const_buffer() {
  2. std::string buf = "hello world!";
  3. asio::const_buffer asio_buf(buf.c_str(), buf.length());
  4. std::vector<asio::const_buffer> buffers_sequence;
  5. buffers_sequence.push_back(asio_buf);
  6. }

最终buffers_sequence就是可以传递给发送接口send的类型。但是这太复杂了,可以直接用buffer函数转化为send需要的参数类型

  1. void use_buffer_str() {
  2. asio::const_buffers_1 output_buf = asio::buffer("hello world");
  3. }

output_buf可以直接传递给该send接口。我们也可以将数组转化为send接受的类型

  1. void use_buffer_array(){
  2. const size_t BUF_SIZE_BYTES = 20;
  3. std::unique_ptr<char[] > buf(new char[BUF_SIZE_BYTES]);
  4. auto input_buf = asio::buffer(static_cast<void*>(buf.get()), BUF_SIZE_BYTES);
  5. }

对于流式操作,我们可以用streambuf,将输入输出流和streambuf绑定,可以实现流式输入和输出。

  1. void use_stream_buffer() {
  2. asio::streambuf buf;
  3. std::ostream output(&buf);
  4. // Writing the message to the stream-based buffer.
  5. output << "Message1\nMessage2";
  6. // Now we want to read all data from a streambuf
  7. // until '\n' delimiter.
  8. // Instantiate an input stream which uses our
  9. // stream buffer.
  10. std::istream input(&buf);
  11. // We'll read data into this string.
  12. std::string message1;
  13. std::getline(input, message1);
  14. // Now message1 string contains 'Message1'.
  15. }
热门评论

热门文章

  1. 聊天项目(28) 分布式服务通知好友申请

    喜欢(507) 浏览(5803)
  2. 使用hexo搭建个人博客

    喜欢(533) 浏览(11420)
  3. Linux环境搭建和编码

    喜欢(594) 浏览(13063)
  4. Qt环境搭建

    喜欢(517) 浏览(23728)
  5. vscode搭建windows C++开发环境

    喜欢(596) 浏览(80008)

最新评论

  1. 再谈单例模式 secondtonone1:是的,C++11以后返回局部static变量对象能保证线程安全了。
  2. 类和对象 陈宇航:支持!!!!
  3. 聊天项目(9) redis服务搭建 pro_lin:redis线程池的析构函数,除了pop出队列,还要free掉redis连接把
  4. Qt MVC结构之QItemDelegate介绍 胡歌-此生不换:gpt, google
  5. 面试题汇总(一) secondtonone1:看到网络上经常提问的go的问题,做了一下汇总,结合自己的经验给出的答案,如有纰漏,望指正批评。
  6. protobuf配置和使用 熊二:你可以把dll放到系统目录,也可以配置环境变量,还能把dll丢到lib里
  7. 堆排序 secondtonone1:堆排序非常实用,定时器就是这个原理制作的。
  8. 创建项目和编译 secondtonone1:谢谢支持
  9. 构造函数 secondtonone1:构造函数是类的基础知识,要着重掌握
  10. 解决博客回复区被脚本注入的问题 secondtonone1:走到现在我忽然明白一个道理,无论工作也好生活也罢,最重要的是开心,即使一份安稳的工作不能给我带来事业上的积累也要合理的舍弃,所以我还是想去做喜欢的方向。
  11. C++ 并发三剑客future, promise和async Yunfei:大佬您好,如果这个线程池中加入的异步任务的形参如果有右值引用,这个commit中的返回类型推导和bind绑定就会出现问题,请问实际工程中,是不是不会用到这种任务,如果用到了,应该怎么解决?
  12. string类 WangQi888888:确实错了,应该是!isspace(sind[index]). 否则不进入循环,还是原来的字符串“some string”
  13. 答疑汇总(thread,async源码分析) Yagus:如果引用计数为0,则会执行 future 的析构进而等待任务执行完成,那么看到的输出将是 这边应该不对吧,std::future析构只在这三种情况都满足的时候才回block: 1.共享状态是std::async 创造的(类型是_Task_async_state) 2.共享状态没有ready 3.这个future是共享状态的最后一个引用 这边共享状态类型是“_Package_state”,引用计数即使为0也不应该block啊
  14. 处理网络粘包问题 zyouth: //消息的长度小于头部规定的长度,说明数据未收全,则先将部分消息放到接收节点里 if (bytes_transferred < data_len) { memcpy(_recv_msg_node->_data + _recv_msg_node->_cur_len, _data + copy_len, bytes_transferred); _recv_msg_node->_cur_len += bytes_transferred; ::memset(_data, 0, MAX_LENGTH); _socket.async_read_some(boost::asio::buffer(_data, MAX_LENGTH), std::bind(&CSession::HandleRead, this, std::placeholders::_1, std::placeholders::_2, shared_self)); //头部处理完成 _b_head_parse = true; return; } 把_b_head_parse = true;放在_socket.async_read_some前面是不是更好
  15. 利用栅栏实现同步 Dzher:作者你好!我觉得 std::thread a(write_x); std::thread b(write_y); std::thread c(read_x_then_y); std::thread d(read_y_then_x); 这个例子中的assert fail并不会发生,原子变量设定了非relaxed内存序后一个线程的原子变量被写入,那么之后的读取一定会被同步的,c和d线程中只可能同时发生一个z++未执行的情况,最终z不是1就是2了,我测试了很多次都没有assert,请问我这个观点有什么错误,谢谢!
  16. 网络编程学习方法和图书推荐 Corleone:啥程度可以找工作
  17. visual studio配置boost库 一giao里我离giaogiao:请问是修改成这样吗:.\b2.exe toolset=MinGW
  18. 聊天项目(7) visualstudio配置grpc diablorrr:cmake文件得改一下 find_package(Boost REQUIRED COMPONENTS system filesystem),要加上filesystem。在target_link_libraries中也同样加上
  19. boost::asio之socket的创建和连接 项空月:发现一些错别字 :每隔vector存储  是不是是每个. asio::mutable_buffers_1 o或者    是不是多打了个o
  20. 聊天项目(15) 客户端实现TCP管理者 lkx:已经在&QTcpSocket::readyRead 回调函数中做了处理了的。
  21. interface应用 secondtonone1:interface是万能类型,但是使用时要转换为实际类型来使用。interface丰富了go的多态特性,也降低了传统面向对象语言的耦合性。
  22. 无锁并发队列 TenThousandOne:_head  和 _tail  替换为原子变量。那里pop的逻辑,val = _data[h] 可以移到循环外面吗
  23. Qt 对话框 Spade2077:QDialog w(); //这里是不是不需要带括号

个人公众号

个人微信