Linuxc/C ++ programming BASICS (28) "Heartbeat" Information Processing

Source: Internet
Author: User

Preface: the previous articles have already described the server. Here we add the client

1. Implement the client. cpp function as follows:

1. Implementation of constructor:
Client: client (): writable (true ){
If (epfd = epoll_create (maxevents) =-1 ){
Exit (-1 );
}
If (connfd = epoll_create (maxevents) =-1 ){
Exit (-1 );
}
Tcpfd =: socket (af_inet, sock_stream, 0 );
Udpfd =: socket (af_inet, sock_dgram, 0 );
Epevent. Events = epollet | epollin | epollout;
}

2. Implement the connection function as follows:
Void client: connect (STD: String host, int port ){
Int rc = 1;
Int flags = 0;
Struct sockaddr_in tcpaddr;
Tcpaddr. sin_family = af_inet;
Tcpaddr. sin_port = htons (port );

Tcpaddr. sin_addr.s_addr =: inet_addr (host. c_str ());

If (rc =: connect (tcpfd, (struct sockaddr *) & tcpaddr, sizeof (struct sockaddr_in) <0 ){
Printf ("[client: connect] TCP connect failed. \ n ");
Writable = false;
Rc = 1;
Return;
}
If (epoll_ctl (epfd, epoll_ctl_add, tcpfd, & epevent) =-1 ){
Printf ("[client: connect] epadd TCP failed: % s", strerror (errno ));
Return;
} Else {
Printf ("[client: connect] epadd TCP successfully. \ n ");
}
}

3. The epoll event listening is as follows:
Void client: ephandle (){
Int n =-1;
N = epoll_wait (epfd, events, maxevents, 0 );
For (INT I = 0; I <n; ++ I ){
If (events [I]. Events & (epollerr | epollhup )){
Printf ("[client: connhandle] epoll err. \ n ");
Continue;
}
If (events [I]. Events & epollout ){
# Ifdef open_log
Printf ("[client: ephandle] epollout event happen. \ n ");
# Endif
}
If (events [I]. Events & epollin ){
# Ifdef open_log
Printf ("[client: ephandle] epollin event happen. \ n ");
# Endif
Recvdata ();
}
}
}

4. Send the logon message as follows:
Int client: sendloginreq (){
Int rc = 1;
Char Buf [50] = {0 };
Int offset = 0;
JSON: Value JV;
JSON: fastwriter writer;
Int uri = 3;
STD: String MSG = "USTC ";
JV ["Uri"] = JSON: Value (URI );
JV ["MSG"] = JSON: Value (MSG );
STD: String loginreq = writer. Write (jv );
Offset + = sprintf (BUF, "% 04d", loginreq. Size ());
Offset + = sprintf (BUF + offset, "% s", loginreq. c_str ());
# Ifdef open_log
Printf ("[client: sendloginreq] loginreq size is % d \ n", loginreq. Size ());
Printf ("[client: sendloginreq] offset is % d \ n", offset );
# Endif
If (writable & (rc =: Send (tcpfd, Buf, offset, msg_dontwait ))
! = Offset & errno = eagain ){
Printf ("[client: sendloginreq] Send eagain, modify writable status. \ n ");
Writable = false;
Rc = 1;
} Else {
Printf ("[client: sendloginreq] Send loginreq successfully. \ n ");
}
Return RC;
}

5. Implementation of response messages:
Void client: canceloginres (){
Printf ("[client: canceloginres] handle login res. \ n ");
}

Void client: paiepingres (){
Printf ("[client: receivepingres] handle Ping res. \ n ");
}

Void client: handle (const char * pack, int length ){
JSON: Value V;
JSON: reader;
If (reader. parse (pack, V )){
Int uri = V ["Uri"]. asuint ();
STD: String MSG = V ["MSG"]. asstring ();
Switch (URI ){
Case ploginres:
Canceloginres ();
Break;
Case ppingres:
Receivepingres ();
Break;
Default:
Printf ("[client: handle] unknown URI: % d \ n", Uri );
Break;
}
}
}

Void client: recvdata (){
Int lenexpected = 0;
Int lenread = 0;
Int rc = 0;
Char Buf [buffersize] = {0 };
If (tcpfd =-1 ){
Return;
}
If (lenread =: Recv (tcpfd, Buf, 4, msg_dontwait ))! = 4 ){
Printf ("[client: canceloginres] Recv bytes is not equal to 4 \ n ");
}
Lenexpected = getlength (BUF );
If (lenread =: Recv (tcpfd, Buf, lenexpected, msg_dontwait) <lenexpected ){
Printf ("[client: canceloginres] Recv bytes less than expected. \ n ");
}
# Ifdef open_log
Printf ("[client: canceloginres] Recv data is % s \ n", Buf );
# Endif
Handle (BUF, lenexpected );

}


6. Send the ping heartbeat information as follows:
Void client: sendpingreq (){
Int rc = 1;
Char Buf [50] = {0 };
Int offset = 0;
JSON: Value JV;
JSON: fastwriter writer;
Int uri = 5;
STD: String MSG = "linyanwen ";
JV ["Uri"] = JSON: Value (URI );
JV ["MSG"] = JSON: Value (MSG );
STD: String pingreq = writer. Write (jv );
# Ifdef open_log
Printf ("[client: sendpingreq] pingreq size: % d \ n", pingreq. Size ());
Printf ("[client: sendpingreq] JSON message is % s", pingreq. c_str ());
# Endif
Offset + = sprintf (BUF, "% 04d", pingreq. Size ());
Offset + = sprintf (BUF + offset, "% s", pingreq. c_str ());
# Ifdef open_log
Printf ("[client: sendpingreq] offset size: % d \ n", offset );
# Endif
If (writable & (rc =: Send (tcpfd, Buf, offset, msg_dontwait ))
! = Pingreq. Size () & errno = eagain ){
Printf ("[client: sendloginreq] Send eagain, modify writable status. \ n ");
Writable = false;
Rc = 1;
} Else {
# Ifdef open_log
Printf ("[client: sendpingreq] Send pingreq successfully. \ n ");
# Endif
}

}

Note: The code is concise and clear.

Ii. Implement the main. cpp function as follows:

# Include <poco/thread. h>
# Include <poco/runnable. h>
# Include <poco/mutex. h>
# Include "timer. H"
# Include "client. H"
Using poco: mutex;
Mutex;
Client CLI;
Void Ping (INT ){
Mutex: scopedlock lock (mutex );
CLI. sendpingreq ();
}
Void loop (INT ){
Mutex: scopedlock lock (mutex );
CLI. ephandle ();
}
Class loopthread: Public poco: runnable {
Virtual void run (){
Printf ("[loopthread: Run] ~~~~~ Invoke ~~~~~ \ N ");
While (1 ){
Loop (1 );
}
}
};
Class pingthread: Public poco: runnable {
Virtual void run (){
Printf ("[pingthread: Run] ~~~~~ Invoke ~~~~~ \ N ");
While (1 ){
Ping (1 );
Sleep (5 );
}
}
};
Int main (INT argc, char ** argv ){
STD: String host = "your server IP Address ";
Int Port = 9999;
// Connect
CLI. Connect (host, Port );
// EP listen
Loopthread logoff;
Poco: thread listenthread ("listen ");
Listenthread. Start (logoff );
// Send login req
CLI. sendloginreq ();
// Ping
Pingthread Pinger;
Poco: thread pingthread ("ping"); // open up another thread to send ping Information
Pingthread. Start (pinger );
Listenthread. Join ();
Pingthread. Join ();
Return 0;
}

3. The running result is as follows:

1. Client running result:

2. server running result:

Note: The running result of the server is the ping information sent by three clients at the same time, and only one of the running results is provided on the client.

Reprinted please indicate the source: zhujian blog, http://blog.csdn.net/linyanwen99/article/details/8315899

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.