This article describes the first example: five simple TCP Network service protocols, including Echo (RFC 862), Discard (RFC 863), Chargen (RFC 864), Daytime (RFC 867), Time (RFC 868), and time The client of the Protocol. The functions of each agreement are as follows:
* Discard-discard all data received;
* Daytime-service-side accept connection, send the current time as a string, and then actively disconnect;
* Time-service-side accept connection, send the current (from Epoch to current number of seconds) in binary form, and then actively disconnect; We need a client program to convert the time we receive to a string.
* echo-echoing service to send the received data back to the client;
* Chargen-server-side accept connection, continuously send test data.
The above five protocols use different ports and can be implemented in the same process without having to use multithreading. Complete code See muduo/examples/simple, download Address http://muduo.googlecode.com/files/muduo-0.1.6-alpha.tar.gz.
Discard
Discard I'm afraid it's the simplest long connection TCP Application layer protocol, which only needs to focus on the "message/Data Arrival" event in "three half events", the event handler function is as follows:
1:void discardserver::onmessage (CONST muduo::net::tcpconnectionptr& conn,
2:muduo::net::buff er* buf,
3:muduo::timestamp time)
4: {
5:string msg (buf->retrieveasstring ()); Retrieve all the data read
6:log_info << conn->name () << "discards" << msg.size () << "bytes at "<< time.tostring ();
7:}
All that's left is the routine code:
Defines a Discardserver class, with TCPServer as a member.
1: #ifndef muduo_examples_simple_discard_discard_h
2: #define MUDUO_EXAMPLES_SIMPLE_DISCARD_DISCARD_H
3:
4: #include <muduo/net/TcpServer.h>
5:
6://RFC 863
7:class discardserver
8: { c8/> 9:public:
10:discardserver (muduo::net::eventloop* loop,
11:const muduo::net::ine taddress& listenaddr);
:
13:void start ();
15:private:
16:void onConnection (const muduo::net::tcpconnectionptr& conn);
:
18:void onMessage (const muduo::net::tcpconnectionptr& conn,
19:muduo::net::buf fer* buf,
20:muduo::timestamp time);
:
22:muduo::net::eventloop* loop_;
23:muduo::net::tcpserver Server_;
:};
:
#endif//Muduo_examples_simple_discard_discard_h