Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use MIME::Base64;
- use Mojolicious::Lite;
- # Template with browser-side code
- get '/' => 'index';
- # WebSocket echo service
- websocket '/echo' => sub {
- my $self = shift;
- # Connected
- $self->app->log->debug('WebSocket connected.');
- # Incoming message
- $self->on('message' => sub {
- my ($self, $message) = @_;
- $self->send_message("echo: $message");
- });
- # Disconnected
- $self->on('finish' => sub {
- my $self = shift;
- $self->app->log->debug('WebSocket disconnected.');
- });
- };
- app->start;
- __DATA__
- @@ index.html.ep
- <!DOCTYPE html>
- <html>
- <head><title>Echo</title></head>
- <body>
- <script>
- var ws = new WebSocket('<%= url_for('echo')->to_abs %>');
- // Incoming messages
- ws.onmessage = function(event) {
- document.body.innerHTML += event.data + '<br/>';
- };
- // Close
- ws.onclose = function() {
- document.body.innerHTML += 'Disconected <br/>';
- };
- // Outgoing messages
- window.setInterval(function() {
- ws.send('Hello Mojo!');
- }, 1000);
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement