forked from elhayra/tcp_server_client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_example.cpp
79 lines (66 loc) · 2.09 KB
/
client_example.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
///////////////////////////////////////////////////////////
/////////////////////CLIENT EXAMPLE////////////////////////
///////////////////////////////////////////////////////////
#ifdef CLIENT_EXAMPLE
#include <iostream>
#include <signal.h>
#include "include/tcp_client.h"
TcpClient client;
// on sig_exit, close client
void sig_exit(int s)
{
std::cout << "Closing client..." << std::endl;
pipe_ret_t finishRet = client.finish();
if (finishRet.success) {
std::cout << "Client closed." << std::endl;
} else {
std::cout << "Failed to close client." << std::endl;
}
exit(0);
}
// observer callback. will be called for every new message received by the server
void onIncomingMsg(const char * msg, size_t size) {
std::cout << "Got msg from server: " << msg << std::endl;
}
// observer callback. will be called when server disconnects
void onDisconnection(const pipe_ret_t & ret) {
std::cout << "Server disconnected: " << ret.msg << std::endl;
std::cout << "Closing client..." << std::endl;
pipe_ret_t finishRet = client.finish();
if (finishRet.success) {
std::cout << "Client closed." << std::endl;
} else {
std::cout << "Failed to close client: " << finishRet.msg << std::endl;
}
}
int main() {
//register to SIGINT to close client when user press ctrl+c
signal(SIGINT, sig_exit);
// configure and register observer
client_observer_t observer;
observer.wantedIp = "127.0.0.1";
observer.incoming_packet_func = onIncomingMsg;
observer.disconnected_func = onDisconnection;
client.subscribe(observer);
// connect client to an open server
pipe_ret_t connectRet = client.connectTo("127.0.0.1", 65123);
if (connectRet.success) {
std::cout << "Client connected successfully" << std::endl;
} else {
std::cout << "Client failed to connect: " << connectRet.msg << std::endl;
return EXIT_FAILURE;
}
// send messages to server
while(1)
{
std::string msg = "hello server\n";
pipe_ret_t sendRet = client.sendMsg(msg.c_str(), msg.size());
if (!sendRet.success) {
std::cout << "Failed to send msg: " << sendRet.msg << std::endl;
break;
}
sleep(1);
}
return 0;
}
#endif