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. Linux环境搭建和编码

    喜欢(594) 浏览(5318)
  2. C++ 类的继承封装和多态

    喜欢(588) 浏览(2475)
  3. 解密定时器的实现细节

    喜欢(566) 浏览(1774)
  4. slice介绍和使用

    喜欢(521) 浏览(1655)
  5. windows环境搭建和vscode配置

    喜欢(587) 浏览(1690)

最新评论

  1. 类和对象 陈宇航:支持!!!!
  2. 泛型算法的定制操作 secondtonone1:lambda和bind是C11新增的利器,善于利用这两个机制可以极大地提升编程安全性和效率。
  3. 基于锁实现线程安全队列和栈容器 secondtonone1:我是博主,你认真学习的样子的很可爱,哈哈,我画的是链表由空变成1个的情况。其余情况和你思考的类似,只不过我用了一个无效节点表示tail的指向,最初head和tail指向的都是这个节点。
  4. 解决博客回复区被脚本注入的问题 secondtonone1:走到现在我忽然明白一个道理,无论工作也好生活也罢,最重要的是开心,即使一份安稳的工作不能给我带来事业上的积累也要合理的舍弃,所以我还是想去做喜欢的方向。
  5. 利用内存模型优化无锁栈 卡西莫多的礼物:感谢博主指点,好人一生平安o(* ̄▽ ̄*)ブ

个人公众号

个人微信