-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.cpp
More file actions
65 lines (52 loc) · 1.53 KB
/
Client.cpp
File metadata and controls
65 lines (52 loc) · 1.53 KB
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
#include "Network.h"
#include <iostream>
#include <cstring>
class Client {
public:
Client(asio::io_service& service);
~Client();
void connect(const asio::ip::tcp::endpoint& ep);
void onConnect(const std::error_code& e);
void writeHeader();
void onHeaderWrite(const std::error_code& e, const std::size_t bytes);
private:
asio::ip::tcp::socket socket_;
char buffer_[BUFFER_SIZE];
};
Client::Client(asio::io_service& service)
: socket_(service)
{
}
void Client::connect(const asio::ip::tcp::endpoint& ep) {
socket_.async_connect(ep, std::bind(&Client::onConnect, this, std::placeholders::_1));
}
void Client::onConnect(const std::error_code& e) {
if (!e) {
std::cout << "Connected to the server, writing header" << std::endl;
writeHeader();
} else {
std::cout << "Connect error: " << e.message() << std::endl;
}
}
void Client::writeHeader() {
std::strcpy(buffer_, "Hello!");
asio::async_write(socket_, asio::buffer(buffer_, HEADER_SIZE),
std::bind(&Client::onHeaderWrite, this, std::placeholders::_1, std::placeholders::_2));
}
void Client::onHeaderWrite(const std::error_code& e, const std::size_t bytes) {
if (!e) {
std::cout << "Header sent, size: " << bytes << std::endl;
} else {
std::cout << "Header write error: " << e.message() << std::endl;
}
}
Client::~Client() {
}
int main() {
asio::io_service service;
Client c(service);
asio::ip::tcp::endpoint ep(asio::ip::address_v4::from_string("127.0.0.1"), 8096);
c.connect(ep);
service.run();
return 0;
}