Skip to content

Instantly share code, notes, and snippets.

@afresh1
Created December 14, 2012 04:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afresh1/4282686 to your computer and use it in GitHub Desktop.
Save afresh1/4282686 to your computer and use it in GitHub Desktop.
This is a [Mojolicious](http://mojolicio.us) streaming http server that opens a [tcpbench](http://www.openbsd.org/cgi-bin/man.cgi?query=tcpbench) connection to back to you. For me this lets me put the page on my server on the net and connect back to my home system and see the results on anything with a web browser. Mostly based on the [EventSour…
#!/usr/bin/perl
# Start this on a server someplace with tcpbench
# Start tcpbench -s on a machine that is the remote IP you are connecting the the web from
# Browse to the page.
use Mojolicious::Lite;
use Mojo::IOLoop;
use Mojo::IOLoop::Stream;
# Template with browser-side code
get '/' => sub {
my $c = shift;
$c->stash->{remote_address} = $c->tx->{remote_address};
} => 'index';
# EventSource for log messages
get '/events' => sub {
my $self = shift;
# Increase inactivity timeout for connection a bit
Mojo::IOLoop->stream( $self->tx->connection )->timeout(300);
# Change content type
$self->res->headers->content_type('text/event-stream');
my $host = $self->tx->{'remote_address'};
my $pid = open my $fh, '-|', 'tcpbench', $host or die $!;
my $stream = Mojo::IOLoop::Stream->new($fh);
my $cb = $stream->on(
read => sub {
my ( $stream, $chunk ) = @_;
$self->write("event:log\ndata: $chunk\n");
}
);
# Unsubscribe from "message" event again once we are done
$self->on(
finish => sub {
my $self = shift;
kill 3, $pid;
$stream->close;
$stream->unsubscribe( read => $cb );
$stream->stop;
}
);
$stream->start;
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title>tcpbench to <%= $remote_address %></title></head>
<body style="font-family: monospace">
<h1>TCPBench to <%= $remote_address %></h1>
<script>
var events = new EventSource('<%= url_for 'events' %>');
// Subscribe to "log" event
events.addEventListener('log', function(event) {
document.body.innerHTML += event.data + '<br/>';
window.scrollTo(0,document.body.scrollHeight);
}, false);
</script>
</body>
</html>
@afresh1
Copy link
Author

afresh1 commented Dec 14, 2012

Not sure why the description isn't Markdown, but Ok. Also not sure why I have to kill it, not just close it but it wouldn't just close.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment