-
Notifications
You must be signed in to change notification settings - Fork 0
/
house
executable file
·63 lines (54 loc) · 1.71 KB
/
house
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
#!/usr/bin/env perl
# house -- server for birdhouse
use Mojolicious::Lite;
use Mojo::JSON;
$ENV{MOJO_INACTIVITY_TIMEOUT} = 60 * 60;
app->secrets([rand 1]);
app->log->level('debug');
# client connects to /door and says hello
my %birds;
sub wall {
my $msg = shift;
#app->log->debug("sending msg $msg->{msg}");
$_->send({ json => $msg }) for values %birds;
}
websocket '/door' => sub {
my $c = shift;
$c->on(message =>
sub {
my ( $c, $msg ) = @_;
$msg =~ /hello, i am (.*)$/
or return $c->app->debug("invalid greeting '$msg'");
my $id = $1;
return $c->app->debug('reserved id "server"')
if $id eq 'server'; # reserved
$c->app->log->debug("connect from $id");
$birds{$id} = $c->tx;
$c->tx->send( { json => { id => 'server', birds => [keys %birds] }} );
$c->on(finish =>
sub {
$c->app->log->debug("disconnect from $id");
delete $birds{$id};
wall { id => 'server', msg => "$id has left", birds => [keys %birds] };
}
);
wall { id => 'server', msg => "$id has joined", birds => [keys %birds] };
$c->tx->unsubscribe('message');
$c->tx->on(message =>
sub {
my ( $tx, $msg ) = @_;
wall { id => $id, msg => $msg };
}
);
}
);
};
Mojo::IOLoop->recurring(10 => sub {
app->log->debug("Connections : ".keys %birds);
} );
app->start;
__DATA__
@@ exception.html.ep
ERROR : <%== stash 'exception' %>
@@ not_found.html.ep
NOT FOUND : <%== $self->req->url->path %>