-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.pl
executable file
·90 lines (72 loc) · 1.8 KB
/
chat.pl
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
#!/usr/bin/env perl
use utf8;
use Mojolicious::Lite;
use DateTime;
Mojo::IOLoop->singleton->max_connections(100000)->start;
get '/' => 'index';
my $clients = {};
websocket '/echo' => sub {
my $self = shift;
app->log->debug(sprintf 'Client connected: %s', $self->tx);
my $id = sprintf "%s", $self->tx;
$clients->{$id} = $self->tx;
$self->on(message => sub {
my ($self, $msg) = @_;
my $dt = DateTime->now( time_zone => 'Asia/Tokyo');
for (keys %$clients) {
$clients->{$_}->send({json => {
hms => $dt->hms,
text => $msg,
}});
}
});
$self->on(finish => sub {
app->log->debug('Client disconnected');
delete $clients->{$id};
});
};
app->start;
__DATA__
@@ index.html.ep
<html>
<head>
<title>WebSocket Client</title>
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
></script>
<script type="text/javascript" src="/js/ws.js"></script>
<style type="text/css">
textarea {
width: 40em;
height:10em;
}
</style>
</head>
<body>
<h1>Mojolicious + WebSocket</h1>
<p><input type="text" id="msg" /></p>
<textarea id="log" readonly></textarea>
</body>
</html>
@@ js/ws.js
$(function () {
$('#msg').focus();
var log = function (text) {
$('#log').val( $('#log').val() + text + "\n");
};
var ws = new WebSocket('ws://localhost:3000/echo');
ws.onopen = function () {
log('Connection opened');
};
ws.onmessage = function (msg) {
var res = JSON.parse(msg.data);
log('[' + res.hms + '] ' + res.text);
};
$('#msg').keydown(function (e) {
if (e.keyCode == 13 && $('#msg').val()) {
ws.send($('#msg').val());
$('#msg').val('');
}
});
});