-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
64 lines (50 loc) · 1.26 KB
/
client.cpp
File metadata and controls
64 lines (50 loc) · 1.26 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
#include "pch.hpp"
using asio::ip::tcp;
void send_loop(tcp::socket& socket, const std::string& username) {
std::string line;
while (std::getline(std::cin, line)) {
std::string msg = username + ": " + line + "\n";
std::error_code ec;
asio::write(socket, asio::buffer(msg), ec);
if (ec) {
std::cerr << "Send error: " << ec.message() << std::endl;
break;
}
}
}
void receive_loop(tcp::socket& socket) {
std::array<char, 1024> buf;
std::error_code ec;
while (true) {
size_t len = socket.read_some(asio::buffer(buf), ec);
if (ec == asio::error::eof) {
std::cout << "Disconnected from server\n";
break;
} else if (ec) {
std::cerr << "Receive error: " << ec.message() << "\n";
break;
}
std::cout.write(buf.data(), len);
std::cout << std::endl;
}
}
int main(int argc, char* argv[]) {
if (argc < 3) {
std::cerr << "Usage: client <port> <username>\n";
return 1;
}
try {
asio::io_context io;
tcp::resolver resolver(io);
auto endpoints =
resolver.resolve("localhost", argv[1]);
tcp::socket socket(io);
asio::connect(socket, endpoints);
std::thread sender(send_loop, std::ref(socket), argv[2]);
receive_loop(socket);
sender.join();
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}