One: What is St_asio_wrapper
It is a C/S network programming framework, based on the packaging of Boost.asio (minimum on the boost-1.49.0 debug), the purpose is to quickly build a C/s system;
Two: Characteristics of St_asio_wrapper
High efficiency, cross-platform, completely asynchronous, of course, this is inherited from Boost.asio;
Automatic re-connection, data transparent transmission, automatically solve the problem of sub-packet sticky packets (must use the default packaging solution, this feature behaves like UDP);
Only TCP and UDP protocols are supported;
Three: The general structure of St_asio_wrapper
St_asio_wrapper.h:
Compiler version test, update log, etc.;
St_asio_wrapper_base.h:
Store some global classes, functions, macros, and log output.
St_asio_wrapper_timer.h (class St_timer):
Timer class, the following classes are required, in addition to packaging and unpacking device;
St_asio_wrapper_socket.h (class St_socket):
St_tcp_socket and St_udp_socket base class, mainly responsible for the message distribution related functions;
St_asio_wrapper_tcp_socket.h (class St_tcp_socket):
TCP socket class for sending and receiving TCP data, inheriting from St_socket;
St_asio_wrapper_udp_socket.h (class St_udp_socket):
UDP socket class, used for transmitting and receiving UDP data, inheriting from St_socket;
St_asio_wrapper_packer.h (interface I_packer, class Packer):
I_packer is the interface of the Packer, Packer is the st_asio_wrapper of the wrapper;
St_asio_wrapper_unpacker.h (interface I_unpacker, class Unpacker):
The I_unpacker is the interface of the unpacking device, and the Unpacker is the St_asio_wrapper self-brought unpacking device;
St_asio_wrapper_service_pump.h (interface I_service, class St_service_pump):
ASIO Io_servie wrapper class for all service objects running St_asio_wrapper (St_server_base, St_sclient, St_tcp_client_base, St_udp_client_ Base);
St_asio_wrapper_object_pool.h (class St_object_pool):
Object pool, from the original St_server_base abstraction, for St_server_base and st_client inheritance, so, the server and the client (support multiple connections) have the object pool function;
St_asio_wrapper_server.h (class St_server_base):
St_server is the service object class for server, which needs to implement I_server interface for the listener of service side, accepting client request, etc.
St_asio_wrapper_server_socket.h (interface I_server, class St_server_socket):
The former is used to obtain the necessary information from St_server, and to invoke the necessary interface; the latter inherits from St_tcp_socket and is used for transmitting and receiving data from the server;
St_asio_wrapper_connector.h (class St_connector):
Inherit from St_tcp_socket, implement connection server (including reconnection) logic;
St_asio_wrapper_client.h (class St_sclient_base, class St_client_base):
Client-related public logic, such as traversal, is inherited by St_tcp_client_base and St_udp_client_base;
St_asio_wrapper_tcp_client.h (class St_tcp_sclient, class St_tcp_client_base):
The former inherits from St_connector, supports only one connection, the latter supports any number of connections, and they implement some logic in order to be called by St_service_pump;
St_asio_wrapper_udp_client.h (class St_udp_sclient, class St_udp_client_base):
A service object based on a UDP socket;
St_asio_wrapper_ssl.h (class St_ssl_connector_base, Class St_ssl_object_pool, Class St_ssl_server_socket_base, class St_ssl_server_base):
SSL-related class libraries supported by all St_asio_wrapper libraries;
Source Code and routines:
Command line: SVN checkout Http://st-asio-wrapper.googlecode.com/svn/trunk/st-asio-wrapper-read-only
If you open it from the SVN client interface, just enter http://st-asio-wrapper.googlecode.com/svn/trunk/to the address bar
git:https://github.com/youngwolf-project/st_asio_wrapper/, in addition, my resources are also downloaded, but not the latest.
QQ Exchange Group: 198941541
Among the include folders are st_asio_wrapper all classes, asio_client and asio_server mates for demonstrating the simplest data receiving, file_server, and file_client for presentation file transfer, Test_ Client and Asio_server are used for performance testing, udp_client demo UDP communication, they are based on st_asio_wrapper, can be regarded as sample;
Class library (including demo) under the VC has a few warnings, can be safely ignored;
The c++0x features are used extensively in class libraries, including: range-based for loop, lambda expression, nullptr, auto, rvalue reference, generics begin (), and end (), so that at least vc2010 and above versions of the compiler are required. or gcc4.6 above;
In the compiler versions prior to vc2010 and gcc4.6, use a compatible version in the Compatiable_edition folder (note that the compatibility version is not less efficient than the normal version, or even slightly higher);
Recommended in the case of use, or the normal version (or the standard version, which is relative to the compatible version), although the efficiency is not improved, but you use in a complex project, the general version of the efficiency will be high, because the same code, c++0x efficiency is generally higher, in the St_asio_ Wrapper didn't show up because I was particularly optimized for compatible versions (and my use was limited, such as some things that could not be optimized, I just didn't have to use them, I hid them);
Developers need to compile their own boost library, probably Boost.system and boost.thread two libraries.
V: Development Tutorials (client)
Client directly include St_asio_wrapper_client.h, you can implement a simple client, as follows:
//Configuration#defineServer_port 9527#defineForce_to_use_msg_recv_buffer//Force to use the msg recv buffer//Configuration#include".. /include/st_asio_wrapper_tcp_client.h" using namespaceSt_asio_wrapper; #defineQuit_command "Quit"#defineRestart_command "RESTART"#defineReconnect_command "Reconnect"#defineSuspend_command "SUSPEND"#defineResume_command "Resume"intMain () {std::stringstr; St_service_pump Service_pump; St_tcp_sclient client (service_pump); //there is no corresponding Echo client demo as server endpoint//because Echo server with echo client made dead loops, and occupy almost all the network resourceclient.set_server_addr (Server_port+ -, SERVER_IP); //client.set_server_addr (Server_port, ":: 1");//IPv6//client.set_server_addr (Server_port, "127.0.0.1");//IPv4Service_pump.start_service (); while(Service_pump.is_running ()) {std::cin>>str; if(str = =Quit_command) Service_pump.stop_service (); Else if(str = =Restart_command) {Service_pump.stop_service (); Service_pump.start_service (1); } Else if(str = =Reconnect_command) Client.graceful_close (true); //the following-commands demonstrate how to suspend msg sending, no matter recv buffer been used or notElse if(str = =Suspend_command) client.suspend_send_msg (true); Else if(str = =Resume_command) client.suspend_send_msg (false); Elseclient.safe_send_msg (str); } } //Restore Configuration#undefServer_port#undefForce_to_use_msg_recv_buffer//Force to use the msg recv buffer//Restore Configuration
In the above example, the client receives data from the console, invokes safe_send_msg to send the data, and when the data is received, it is output to the console (St_tcp_socket or st_udp_socket implementation);
Among them, Start_service Open service, Stop_service end service (must be explicitly called when exiting), is_running judge the running state of the service; If you want to modify the server-side address, call set_ before calling Start_service SERVER_ADDR function;
After Stop_service, you can call Start_service to start the service again;
If you are not stop_service and want to reconnect directly, call St_connector Force_close or graceful_close with true;
Of course, in general, the client will not just display the received data to the console as simply as it needs to derive a class from St_tcp_sclient or St_udp_sclient (if you have more than one connection, from St_connector or ST_UDP_ Socket to derive a class, and use St_tcp_client or st_udp_client to manage it, please refer to test_client This demo, it supports multiple connections), and then there are two methods for you to choose, one: Rewrite On_ MSG and return it directly to true (or define Force_to_use_msg_recv_buffer macro, as for why you need to read all the St_asio_wrapper a series of four tutorials), and then rewrite On_msg_ Handle and do message processing inside, two: rewrite on_msg, and do message processing inside, then return false. The difference between the two methods is that the former does not block the reception of the message, the latter will, for example, your message processing takes 1 seconds, then in this 1 seconds, the former and receive the message in parallel, the latter can not accept the message until the end of the message processing. Another difference is that the former needs to receive the cache, which is not required. Of course, the blocking here refers to the current socket is blocked, regardless of other sockets, such as on the server, there are two sockets, when you handle the socket 1 message, no matter how you use the previous method, it is not possible to block socket 2 message reception. For this topic, please refer to the fourth tutorial;
Once the message has been sent, you have a chance to be notified that the On_msg_send function is rewritten, and its parameters are the message (note that it is packaged);
Each call send_msg or safe_send_msg, the other party must receive an identical data, two times developers no longer consider the problem of sub-packet sticky (must use the default packaging solution), this feature you can think of it as a UDP behavior;
St_socket There is send message cache, so when two times the developer has the data to send, you can call send_msg at any time (note that the cache is full of problems, safe_send_msg to ensure that the data sent successfully, when the cache is full wait) without worrying about whether the current connection has been established, It will send you the data when the condition is right.
You may need to modify the following categories of macros:
1. Global macros, server-side clients are required to:
The cache space size used by the Unified_out_buf_num:unified_out class, default 2048;
Max_msg_len: Maximum message length (packaged, with the default Packer, it only supports 3998 message lengths, because there is also a 2-byte header), default 4000. For the default packager wrapper, this length range can only be 1 to (65535-2), because the Baotou only uses two bytes, if you want to exceed this limit, you can define HUGE_MSG macros;
Huge_msg: Turn on large message support and turn it off by default. Note that big messages can take up large memory, see Asio_client demo, which has a demo usage (annotation status), and an explanation of the large memory usage;
Max_msg_num: Maximum number of messages per St_socket message cache (receive and send cache pooled, so the total maximum number of message bars is twice times max_msg_num), default 1024;
Enhanced_stability: Enhanced robustness, if you turn on this macro, all service objects will be at the outermost (io_service.run) packet layer try catch to increase robustness, of course, increase the try is a loss of efficiency, this macro is not turned on by default ;
Force_to_use_msg_recv_buffer: Always use the message receive cache, this is the compile time optimization, said before, On_msg () returns true for using the message receive cache, if your on_msg () always return true, you can open this macro, Then St_tcp_socket or St_udp_socket will no longer call on_msg () (There is no virtual function at all) but instead directly put the message into the message receive cache, which can improve some efficiency, the default does not turn on Benhong;
No_unified_out: Let the st_asio_wrapper inside of all output fail;
Custom_log: Custom output, at this point you need to provide 5 log functions, function names and signatures see the Unified_out class, and either static or global.
Default_packer: Custom Packager, which is a class name, must provide a default constructor (that is, a constructor without parameters).
Default_unpacker: A custom Solver, which is a class name, must provide a default constructor (that is, a constructor without parameters).
St_service_thread_num:io the number of threads used to run the Io_service.run function.
Max_object_num: The maximum number of objects supported by the object pool, default 4096;
Reuse_object: Whether to open the object pool, if open, when creating a new object, will try to use the object has been closed, at this time will not automatically release the closed list of objects, see Socket_free_interval macro, the default does not open Benhong;
Socket_free_interval: Before you say this macro, say something about St_object_pool's internal workings: when you call Del_object (the default behavior of St_server_socket in On_recv_error), St_object_pool's approach is not to delete this object, but to move the object into another linked list, the list of objects will be traversed every socket_free_interval seconds, to find that has been closed more than Closed_socket_max _duration a second object, and then really frees it from memory, because when del_object, there may be other asynchronous operations not completed, or completed, but still not distributed in the queue, if the object is freed from memory at this time, then the subsequent asynchronous callback, Memory access may appear to be out of bounds. This problem can be done by binding a shared_ptr for each asynchronous call to the this pointer to this object, but the overuse of shared_ptr can affect efficiency. Unit is seconds, default 10 seconds. If the reuse_object is turned on, then this macro is not used at all (there is no timing traversal), because the closed object has been put into the object pool, waiting to be reused, can not be released;
Auto_clear_closed_socket: Whether the server is timed to call Clear_all_closed_object () to clear the socket that has been closed, if you are not convenient to call Del_object, The object pool will accumulate more and more closed objects (if there is a connection error, or exit), you can open this macro, let st_object_pool for you to do these cleanup work regularly; note that if the list of objects is very large, traversing the linked list can affect efficiency. The traversal interval is defined by Clear_closed_socket_interval and does not open Benhong by default;
Clear_closed_socket_interval: Timed Call Clear_all_closed_object () interval, units in seconds, default 60 seconds, if Auto_clear_closed_socket is not turned on, Then this macro is not used at all (there is no timing call clear_all_closed_object ());
Closed_socket_max_duration: After you close the connection for a few seconds, you can safely dispose of the object or reuse the object (depending on whether the reuse_object is defined, defined as reuse, otherwise freed), and the default is 5 seconds.
2.TCP Client-only macros:
Graceful_close_max_duration: Graceful shutdown, maximum wait time in seconds, default 5.
SERVER_IP: Server IP address, expressed as a string, default "127.0.0.1";
Server_port: Server port, default 5050;
Re_connect_interval: When the connection server fails, how long is the delay reconnection, the unit is milliseconds, the default is 500 milliseconds;
Re_connect_control: After you open this macro, you can control the number of reconnection times and the runtime can also modify it.
3.tcp server-side dedicated macros:
Server_port: Server port (server IP if you want to set, can only call Set_server_addr interface, cannot be implemented by macro), default 5050;
Tcp_default_ip_version: When you do not specify a server-side IP, this macro specifies the version of the IP protocol (v4 or V6, respectively boost::asio::ip::tcp::v4 () and boost::asio::ip::tcp:: V6 ()), if IP is specified, the version is parsed from the IP address;
Async_accept_num: The maximum number of simultaneous delivery of asynchronous ACCEPT calls, default 1;
Not_reuse_address: Turn off port reuse, and UDP uses this macro as well.
4.UDP Client-only macros:
Udp_default_ip_version: When IP is not specified, this macro specifies the version of the IP protocol (v4 or V6, respectively boost::asio::ip::udp::v4 () and BOOST::ASIO::IP::UDP::V6 ( ), if IP is specified, the version is parsed from the IP address;
The above macros can be modified according to the project, you just need to define these macros before the include corresponding St_asio_wrapper related header files, the specific example of the demo inside.
Boost.asio Packaging Class St_asio_wrapper Development tutorial (i)