-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvs22.cpp
73 lines (66 loc) · 2.14 KB
/
vs22.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
#include <iostream>
#include <stdexcept>
#include <string>
#include "caf/all.hpp"
#include "caf/io/all.hpp"
using namespace caf;
behavior writer(event_based_actor* self, const actor& user) {
return {
[=](const std::string& line) {
if (self->current_sender() != user)
std::cout << line << '\n';
},
[=](const group_down_msg&) {
std::cerr << "FATAL: server is down!\nPress ENTER to exit.\n";
fclose(stdin);
},
};
}
struct config : actor_system_config {
config() {
opt_group{custom_options_, "global"}
.add(is_server, "server,s", "run in server mode")
.add(port, "port,p",
"set port for publishing of / connecting to chatrooms")
.add(host, "host,H", "hostname or IP of the chat server")
.add(room, "room,r", "name of the chatroom")
.add(name, "name,n", "username in chat");
}
bool is_server = false;
uint16_t port = 0;
std::string host = "localhost";
std::string room = "vslab";
std::string name = "vslab-student";
};
void caf_main(actor_system& sys, const config& cfg) {
if (cfg.is_server) {
if (auto port = sys.middleman().publish_local_groups(cfg.port)) {
std::cout << ">> running at port " << *port << '\n'
<< ">> press ENTER to stop the server\n";
getc(stdin);
} else {
std::cout << ">> publishing failed: " << to_string(port.error()) << '\n';
}
return;
}
group grp;
std::cout << ">> try to join room " << cfg.room << " on " << cfg.host
<< " at port " << cfg.port << " ...\n";
if (auto rg = sys.middleman().remote_group(cfg.room, cfg.host, cfg.port)) {
grp = std::move(*rg);
std::cout << ">> got group: " << to_string(grp) << '\n';
} else {
std::cerr << ">> failed to get group: " << to_string(rg.error()) << '\n';
return;
}
scoped_actor self{sys};
auto worker = self->spawn_in_group(grp, writer, self);
std::string prefix = cfg.name + ": ";
std::string line;
while (std::getline(std::cin, line)) {
line.insert(line.begin(), prefix.begin(), prefix.end());
self->send(grp, line);
}
self->send_exit(worker, exit_reason::user_shutdown);
}
CAF_MAIN(io::middleman)