1. The implementation of server. cpp on the server side is as follows:
# Include <iostream>
# Include <boost/ASIO. HPP>
# Include <boost/Bind. HPP>
# Include <boost/shared_ptr.hpp>
Using namespace boost;
Using namespace boost: ASIO;
Class server {
PRIVATE:
Io_service & IOS;
IP: TCP: acceptor;
Typedef shared_ptr <IP: TCP: Socket> sock_pt;
Public:
Server (io_service & Io): IOS (IO)
, Acceptor (IOS, IP: TCP: endpoint (IP: TCP: V4 (), 9999 ))
{
Start ();
}
Void start (){
Sock_pt sock (new IP: TCP: socket (IOS ));
Acceptor. async_accept (* sock, BIND (& server: accept_handler, this, placeholders: error, sock ));
}
Void accept_handler (const system: error_code & EC, sock_pt sock ){
If (EC ){
Return;
}
STD: cout <"client :";
STD: cout <sock-> remote_endpoint (). Address () <STD: Endl;
Sock-> async_write_some (buffer ("Hello ASIO"), BIND (& server: write_handler, this, placeholders: Error ));
Start ();
}
Void write_handler (const system: error_code & E ){
STD: cout <"Send message complete." <STD: Endl;
}
};
Int main (INT argc, char ** argv ){
Try {
STD: cout <"Server start." <STD: Endl;
Io_service Ios;
Server SERV (IOS );
IOS. Run ();
} Catch (STD: exception & E ){
STD: cout <E. What () <STD: Endl;
}
Return 0;
}
2. Implementation of client. cpp on the client is as follows:
# Include <iostream>
# Include <vector>
# Include <boost/ASIO. HPP>
# Include <boost/Bind. HPP>
# Include <boost/function. HPP>
# Include <boost/date_time/posix_time/posix_time.hpp>
Using namespace boost;
Using namespace boost: ASIO;
Class client {
PRIVATE:
Io_service & IOS;
IP: TCP: endpoint EP;
Typedef shared_ptr <IP: TCP: Socket> sock_pt;
Public:
Client (io_service & Io): IOS (IO)
, EP (IP: Address: from_string ("127.0.0.1"), 9999)
{
Start ();
}
Void start (){
Sock_pt sock (new IP: TCP: socket (IOS ));
Sock-> async_connect (Ep, BIND (& client: conn_handler, this, placeholders: error, sock ));
}
Void conn_handler (const system: error_code & EC, sock_pt sock ){
If (EC ){
Return;
}
STD: cout <"receive from" <sock-> remote_endpoint (). Address () <STD: Endl;
Shared_ptr <STD: vector <char> STR (new STD: vector <char> (100,0 ));
Sock-> async_read_some (buffer (* Str), BIND (& client: read_handler, this, placeholders: error, STR ));
Start ();
}
Void read_handler (const system: error_code & EC, shared_ptr <STD: vector <char> Str ){
If (EC ){
Return;
}
STD: cout <& (* Str) [0] <STD: Endl;
}
};
Int main (INT argc, char ** argv ){
Try {
STD: cout <"client start." <STD: Endl;
Io_service Ios;
Client CLI (IOS );
IOS. Run ();
} Catch (STD: exception & E ){
STD: cout <E. What () <STD: Endl;
}
Return 0;
}
3. The running result is as follows:
Server:
Client:
References: Full boost Library Development Guide, by Luo Jianfeng
Reprinted please indicate the source: zhujian blog: http://blog.csdn.net/linyanwen99/article/details/8256266