-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
112 lines (74 loc) · 2.66 KB
/
main.cpp
File metadata and controls
112 lines (74 loc) · 2.66 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <nodepp/nodepp.h>
#include <nodepp/listener.h>
#include <nodepp/encoder.h>
#include <nodepp/crypto.h>
#include <apify/apify.h>
#include <nodepp/ws.h>
using namespace nodepp;
listener_t<string_t,bool,string_t> onResponse;
promise_t<string_t,except_t> request( ws_t cli ) {
return promise_t<string_t,except_t>([=]( res_t<string_t> res, rej_t<except_t> rej ){
auto sha = crypto::hash::SHA1();
sha.update( encoder::key::generate( 32 ) );
sha.update( string::to_string( process::now() ) );
auto pid = regex::format( "/${0}", sha.get() );
onResponse.once( pid, [=]( bool fail, string_t message ){
switch( fail ){
case false: res( message ); /*-------*/ break;
default : rej( except_t( message ) ); break;
}
});
apify::add( cli ).emit( "METHOD", pid, "MESSAGE" );
}); }
void client(){
auto srv = ws::client( "ws://localhost:8000" );
auto app = apify::add<ws_t>();
app.on( "DONE", "/:pid", [=]( apify_t<ws_t> cli ){
auto pid=regex::format("/${0}",cli.params["pid"]);
onResponse.emit( pid, 0, cli.message );
});
app.on( "FAIL", "/:pid", [=]( apify_t<ws_t> cli ){
auto pid=regex::format("/${0}",cli.params["pid"]);
onResponse.emit( pid, 1, cli.message );
});
srv.onConnect([=]( ws_t cli ){
cli.onData([=]( string_t data ){
app.next( cli, data );
});
srv.onClose([=](){
console::log("Disconnected");
}); console::log("Connected");
request( cli ).then([=]( string_t message ){
console::log( "->", message );
}).fail([=]( except_t err ){
console::log( "->", err.data() );
});
});
}
void server() {
auto app = apify::add<ws_t>();
auto srv = ws::server();
app.on( "METHOD", "/:pid", [=]( apify_t<ws_t> cli ){
auto pid=regex::format("/${0}",cli.params["pid"]) ; try {
cli.emit( "DONE", pid, "Message received !" );
process::exit(1);
} catch(...) {
cli.emit( "FAIL", pid, "something went wrong" );
process::exit(1);
} });
srv.onConnect([=]( ws_t cli ){
cli.onData([=]( string_t data ){
app.next( cli, data );
});
cli.onClose([=](){
console::log("Disconnected");
}); console::log("Connected");
});
srv.listen("localhost",8000,[=](...){
console::log( "ws:/localhost:8000" );
}); console::log( "Started" );
}
void onMain() {
if( process::env::get("mode") == "server" )
{ server(); } else { client(); }
}