-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.cpp
69 lines (58 loc) · 2.11 KB
/
client.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
// based on https://github.com/eminfedar/async-sockets-cpp
#include <iostream>
#include "tcpsocket.hpp"
#include "json.hpp"
using namespace std;
int main()
{
// Initialize socket.
TCPSocket tcpSocket([](int errorCode, std::string errorMessage){
cout << "Socket creation error:" << errorCode << " : " << errorMessage << endl;
exit(EXIT_FAILURE);
});
// Start receiving from the host.
tcpSocket.onMessageReceived = [](string message) {
cout << "Message from the Server: " << message << endl;
nlohmann::ordered_json j = nlohmann::ordered_json::parse(message);
if (j == nullptr || j["HAND_LEFT"] == nullptr || j["HAND_RIGHT"] == nullptr || j["SPINE_CHEST"] == nullptr) return;
cout << "----> HAND_LEFT: " << j["HAND_LEFT"] << endl;
cout << "----> HAND_RIGHT: " << j["HAND_RIGHT"] << endl;
cout << "----> SPINE_CHEST: " << j["SPINE_CHEST"] << endl;
cout << std::flush;
};
// If you want to use raw bytes instead of std::string:
/*
tcpSocket.onRawMessageReceived = [](const char* message, int length) {
cout << "Message from the Server: " << message << "(" << length << ")" << endl;
};
*/
// On socket closed:
tcpSocket.onSocketClosed = [&tcpSocket](int errorCode){
cout << "Connection closed: " << errorCode << endl;
tcpSocket.Close();
exit(EXIT_SUCCESS);
};
// Connect to the host.
tcpSocket.Connect("localhost", 8888, [] {
cout << "Connected to the server successfully." << endl;
// Send String:
// tcpSocket.Send("Hello Server!");
},
[&tcpSocket](int errorCode, std::string errorMessage){
// CONNECTION FAILED
cout << errorCode << " : " << errorMessage << endl;
tcpSocket.Close();
exit(EXIT_FAILURE);
});
// You should do an input loop so the program will not end immediately:
// Because socket listenings are non-blocking.
string input;
getline(cin, input);
while (input != "exit")
{
// tcpSocket.Send(input);
getline(cin, input);
}
tcpSocket.Close();
return 0;
}