網絡編程基本流程
網絡編程的基本流程對于服務端是這樣的
服務端
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——建立連接后,就可發收消息了。
圖示如下
終端節點的創建
所謂終端節點就是用來通信的端對端的節點,可以通過ip地址和端口構造,其的節點可以連接這個終端節點做通信.
如果我們是客戶端,我們可以通過對端的ip和端口構造一個endpoint,用這個endpoint和其通信。
類"boost:asio:ip:address"沒有成員"from_string”
int client_end_point() {// Step 1. Assume that the client application has already // obtained the IP-address and the protocol port number.std::string raw_ip_address = "127.0.0.1";unsigned short port_num = 3333;// Used to store information about error that happens// while parsing the raw IP-address.boost::system::error_code ec;// Step 2. Using IP protocol version independent address// representation.asio::ip::address ip_address =asio::ip::address::from_string(raw_ip_address, ec);if (ec.value() != 0) {// Provided IP address is invalid. Breaking execution.std::cout<< "Failed to parse the IP address. Error code = "<< ec.value() << ". Message: " << ec.message();return ec.value();}// Step 3.asio::ip::tcp::endpoint ep(ip_address, port_num);// Step 4. The endpoint is ready and can be used to specify a // particular server in the network the client wants to // communicate with.return 0;
}
如果是服務端,則只需根據本地地址綁定就可以生成endpoint
nt server_end_point(){// Step 1. Here we assume that the server application has//already obtained the protocol port number.unsigned short port_num = 3333;// Step 2. Create special object of asio::ip::address class// that specifies all IP-addresses available on the host. Note// that here we assume that server works over IPv6 protocol.asio::ip::address ip_address = asio::ip::address_v6::any();// Step 3.asio::ip::tcp::endpoint ep(ip_address, port_num);// Step 4. The endpoint is created and can be used to // specify the IP addresses and a port number on which // the server application wants to listen for incoming // connections.return 0;
}
創建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 dns_connect_to_end() {std::string host = "llfc.club";//域名std::string port_num = "3333";asio::io_context ioc;boost::asio::ip::tcp::resolver resolver(ioc);//asio::ip::tcp::resolver::query resolver_query(host,port_num,asio::ip::tcp::resolver::query::numeric_service);//DNS解析器try{auto endpoints = resolver.resolve(host, port_num);//創建socket并連接到對應的地址asio::ip::tcp::socket sock(ioc);asio::connect(sock, endpoints);}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();}
}
關于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::vectorasio::mutable_buffer
結構如下
每隔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類型
void use_stream_buffer() {asio::streambuf buf;std::ostream output(&buf);// Writing the message to the stream-based buffer.output << "Message1\nMessage2";// Now we want to read all data from a streambuf// until '\n' delimiter.// Instantiate an input stream which uses our // stream buffer.std::istream input(&buf);// We'll read data into this string.std::string message1;std::getline(input, message1);// Now message1 string contains 'Message1'.
}