-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathtcp-client.cpp
52 lines (42 loc) · 1.44 KB
/
tcp-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
#include "tcpsocket.hpp"
#include <iostream>
using namespace std;
int main()
{
// Initialize socket.
TCPSocket<> tcpSocket([](int errorCode, std::string errorMessage){
cout << "Socket creation error:" << errorCode << " : " << errorMessage << endl;
});
// Start receiving from the host.
tcpSocket.onRawMessageReceived = [](const char* message, int length) {
cout << "Message from the Server: " << message << "(" << length << ")" << endl;
};
// If you want to use std::string instead of const char*:
//tcpSocket.onMessageReceived = [](string message) {
// cout << "Message from the Server: " << message << endl;
//};
// On socket closed:
tcpSocket.onSocketClosed = [](int errorCode){
cout << "Connection closed: " << errorCode << endl;
};
// Connect to the host (with a custom buffer size).
tcpSocket.Connect("localhost", 8888, [&] {
cout << "Connected to the server successfully." << endl;
// Send String:
tcpSocket.Send("Hello Server!");
},
[](int errorCode, std::string errorMessage){
// CONNECTION FAILED
cout << errorCode << " : " << errorMessage << endl;
});
// You should do an input loop, so the program won't terminate immediately
string input;
getline(cin, input);
while (input != "exit")
{
tcpSocket.Send(input);
getline(cin, input);
}
tcpSocket.Close();
return 0;
}