Skip to content

Instantly share code, notes, and snippets.

@yevrah
Created July 31, 2015 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yevrah/4ad89920da9d35393a15 to your computer and use it in GitHub Desktop.
Save yevrah/4ad89920da9d35393a15 to your computer and use it in GitHub Desktop.
Perl: Simple echo server using mojo
#!/usr/bin/env perl
# Usage:
# perl echo.pl daemon
use Mojolicious::Lite;
get '/' => 'index';
websocket '/echo' => sub {
my $self = shift;
$self->on(message => sub {
my ($self, $msg) = @_;
my ($s,$m,$h)=localtime(time);
$self->send({ json => { text => $msg, time=> "$h:$m:$s" }});
});
};
app->start;
__DATA__
@@ index.html.ep
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" ></script>
<script type="text/javascript" charset="utf-8">
$(function () {
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.time + '> ' + res.text);
};
$('#msg').keydown(function (e) {
if (e.keyCode == 13 && $('#msg').val()) {
ws.send($('#msg').val());
$('#msg').val('');
}
});
});
</script>
</head>
<body>
<input type="text" id="msg" placeholder="Type Your Message Here" /><br>
<textarea id="log" readonly></textarea>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment