File: chat.pl

package info (click to toggle)
libmojolicious-perl 9.31%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,260 kB
  • sloc: perl: 10,139; makefile: 31; javascript: 1
file content (34 lines) | stat: -rw-r--r-- 1,004 bytes parent folder | download | duplicates (3)
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
#
# Minimal single-process WebSocket chat application for browser testing
#
use Mojolicious::Lite -signatures;
use Mojo::EventEmitter;

helper events => sub { state $events = Mojo::EventEmitter->new };

get '/' => 'chat';

websocket '/channel' => sub ($c) {
  $c->inactivity_timeout(3600);

  # Forward messages from the browser
  $c->on(message => sub ($c, $msg) { $c->events->emit(mojochat => $msg) });

  # Forward messages to the browser
  my $cb = $c->events->on(mojochat => sub { $c->send(pop) });
  $c->on(finish => sub ($c, $code, $reason = undef) { $c->events->unsubscribe(mojochat => $cb) });
};

app->start;
__DATA__

@@ chat.html.ep
<form onsubmit="sendChat(this.children[0]); return false"><input></form>
<div id="log"></div>
<script>
  const ws  = new WebSocket('<%= url_for('channel')->to_abs %>');
  ws.onmessage = function (e) {
    document.getElementById('log').innerHTML += '<p>' + e.data + '</p>';
  };
  function sendChat(input) { ws.send(input.value); input.value = '' }
</script>