UDP asynchronous listener and TCP asynchronous sending program implemented by boost ASIO

Source: Internet
Author: User

Http://blog.chinaunix.net/uid-24544542-id-176702.html

The code is rough. I hope my friends can correct me ^ & ^ # include <boost/ASIO/deadline_timer.hpp> # include <boost/ASIO/io_service.hpp> # include <boost/ASIO/IP/TCP. HPP> # include <boost/ASIO/read_until.hpp> # include <boost/ASIO/streambuf. HPP> # include <boost/ASIO/write. HPP> # include <boost/ASIO. HPP> # include <boost/bind. HPP> # include <boost/shared_ptr.hpp> # include <boost/enable_shared_from_this.hpp> # include <iostream> # include "Message. HPP "# define maxlen 1024 # define seconds 5 using namespace STD; using namespace *****: Protocol; using boost: ASIO: deadline_timer; using boost: ASIO: IP: TCP; using boost: ASIO: IP: UDP; class session {public: Session (boost: ASIO :: io_service & io_service, const char * path, int port): stopped _ (false), socket _ (io_service), command _ (io_service, UDP: endpoint (UDP :: v4 (), Port), d Eadline _ (io_service), heartbeat_timer _ (io_service) {callback _ = new callback (PATH); input_stream _ = new char [maxlen];} ~ Session () {Delete callback _; Delete input_stream _;} void start (TCP: resolver: iterator endpoint_iter) {start_connect (endpoint_iter); deadline _. async_wait (boost: BIND (& session: check_deadline, this);} void stop () {stopped _ = true; socket _. close (); deadline _. cancel (); heartbeat_timer _. cancel ();} PRIVATE: void start_connect (TCP: resolver: iterator endpoint_iter) {If (endpoint_iter! = TCP: resolver: iterator () {logs. write_log (normal, "inof: connect --->"); deadline _. expires_from_now (boost: posix_time: seconds (60); socket _. async_connect (endpoint_iter-> endpoint (), boost: BIND (& session: handle_connect, this, _ 1, endpoint_iter);} else {stop ();}} void handle_connect (const boost: System: error_code & EC, TCP: resolver: iterator endpoint_iter) {If (stopped _) return; If (! Socket _. is_open () {logs. write_log (normal, "info: connect Time Out"); start_connect (++ endpoint_iter);} else if (EC) {logs. write_log (normal, "info: connect error"); socket _. close (); start_connect (++ endpoint_iter);} else {// logs. write_log (normal, "info: conected to % s", endpoint_iter-> endpoint (); logs. write_log (normal, "info: conected! "); Start_read (); start_write_heartbeat (); start_delivery () ;}} void start_read () {deadline _. expires_from_now (boost: posix_time: seconds (seconds * 6); socket _. async_receive (boost: ASIO: buffer (& header _, headerlen), boost: BIND (& session: handle_read_header, this, boost: ASIO: placeholders :: error);} void handle_read_header (const boost: System: error_code & EC) {If (stopped _) return; If (! EC) {If (Heartbeat = header _. type) {logs. write_log (normal, "info: receive Heartbeat message --->"); deadline _. expires_from_now (boost: posix_time: seconds (seconds * 6); // heartbeat_timer _. expires_from_now (boost: posix_time: seconds (seconds); start_read ();} else if (packet = header _. type) {logs. write_log (normal, "info: receive packet message --->"); socket _. async_receive (boost: ASIO: buffer (input_strea M _, header _. length), boost: BIND (& session: handle_read_body, this, boost: ASIO: placeholders: Error); logs. write_log (normal, "info: receive % d bytes", header _. length) ;}} else {logs. write_log (normal, "error on receive: % s", (EC. message ()). c_str (); stop () ;}} void handle_read_body (const boost: System: error_code & EC) {If (stopped _) return; If (! EC) {If (packet_message _. parse (input_stream _, header _. length) {packet * packet = packet_message _. pack (); logs. write_log (normal, "info: receive data: % s", (packet-> data ()). c_str (); callback _-> write (packet);} start_read ();} else {logs. write_log (normal, "error on receive: % s", (EC. message ()). c_str (); stop () ;}} void start_write_heartbeat () {If (stopped _) return; header. length = 0; H Eader. type = heartbeat; Boost: ASIO: async_write (socket _, boost: ASIO: buffer (& header, headerlen), boost: BIND (& session: handle_write_heartbeat, this, boost: ASIO: placeholders: Error); logs. write_log (normal, "info: Send Heartbeat message --->");} void handle_write_heartbeat (const boost: System: error_code & EC) {If (stopped _) return; if (! EC) {heartbeat_timer _. expires_from_now (boost: posix_time: seconds (seconds); heartbeat_timer _. async_wait (boost: BIND (& session: start_write_heartbeat, this);} else {logs. write_log (normal, "info: Error on heartbeat: % s", (EC. message ()). c_str (); stop () ;}} void start_delivery () {If (stopped _) return; configure * conf = conf_message _. conf (); header; conf-> set_ip ("10.14.2.40"); conf-> set_conf ("\ D + \ W + *"); conf-> set_file ("/tmp/aaa.txt"); conf-> set_chars ("Hello World "); conf-> set_offset (0); conf_message _. serialize (); header. length = conf_message _. length (); header. type = config; socket _. async_send (boost: ASIO: buffer (& header, headerlen), boost: BIND (& session: handle_write_config, this, boost: ASIO: placeholders :: error);} void handle_write_config (const boost: System: error_code & EC ){ If (stopped _) return; If (! EC) {socket _. async_send (boost: ASIO: buffer (conf_message _. data (), conf_message _. length (), boost: BIND (& session: handle_wait_commander, this, boost: ASIO: placeholders: Error) ;}} void handle_wait_commander (const boost :: system: error_code & EC) {logs. write_log (normal, "info: waiting for the Commander ---> .. ");/** boost: BIND (& session: Delivery ---> .) **/command _. async_receive_from (boost: ASIO:: Buffer (& commander_header _, headerlen), receive_entpoint _, boost: BIND (& session: handle_check_commander, this, boost: ASIO: placeholders: Error ));} void handle_check_commander (const boost: System: error_code & EC) {If (delivery = commander_header _. type | 8888 = commander_header _. length) {logs. write_log (normal, "info: receive a command, delivery a configure");/* boost: BIND (& session: start_deli Very, this, boost: ASIO: placeholders: Error); */start_delivery ();} else {logs. write_log (normal, "error: Bad command format! ") ;}} Void check_deadline () {If (stopped _) return; // check whether the deadline has passed. we compare the deadline against // The current time since a new asynchronous operation may have moved the // deadline before this actor had a chance to run. if (deadline _. expires_at () <= deadline_timer: traits_type: Now () {// The deadline has passed. the socket is closed so that any outstanding // Asyn Chronous operations are canceled. socket _. close (); // There is no longer an active deadline. the expiry is set to positive // infinity so that the actor takes no action until a new deadline is set. deadline _. expires_at (boost: posix_time: pos_infin);} // put the actor back to sleep. deadline _. async_wait (boost: BIND (& session: check_deadline, this);} PRIVATE: bool stopped _; TCP: Socket socket _; u DP: Socket command _; UDP: endpoint receive_entpoint _; header commander_header _; configmessage conf_message _; datamessage packet_message _; heartbeatmessage heartbeat_message _; deadline_timer deadline _; deadline_timer heartbeat_timer _; callback * callback _; char * input_stream _ ;}; int main (INT argc, char * argv []) {try {If (argc! = 4) {STD: cerr <"Usage: session 

Compile:
G ++-wall-g-I/usr/include/Boost-L/usr/lib/Boost easyzlib. O logserver. pb. CC message. CPP daemon. CPP client. CPP-O client-lboost_thread-lboost_system 'pkg-config -- cflags -- libs protobuf'

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.