-
-
Save s1037989/3ee11ada741db23afe29030da673dee3 to your computer and use it in GitHub Desktop.
[Mojolicious] websocket route that polls a database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use Mojolicious::Lite; | |
| use 5.20.0; | |
| use experimental 'signatures'; | |
| use Mojo::IOLoop; | |
| Mojo::IOLoop->recurring(1 => sub { warn scalar localtime }); | |
| # Render template "index.html.ep" from the DATA section | |
| get '/' => {template => 'index'}; | |
| # WebSocket service used by the template to extract the title from a web site | |
| websocket '/title' => sub ($c) { | |
| $c->on(message => sub ($c, $msg) { | |
| my $title = $c->ua->get($msg)->res->dom->at('title')->text; | |
| $c->send($title); | |
| }); | |
| }; | |
| app->start; | |
| __DATA__ | |
| @@ index.html.ep | |
| % my $url = url_for 'title'; | |
| <script> | |
| var ws = new WebSocket('<%= $url->to_abs %>'); | |
| ws.onmessage = function (event) { document.body.innerHTML += event.data }; | |
| ws.onopen = function (event) { ws.send('http://mojolicious.org') }; | |
| </script> | |
| __END__ | |
| $ perl /tmp/ws daemon | |
| [Mon Aug 8 23:13:43 2016] [info] Listening at "http://*:3000" | |
| Server available at http://127.0.0.1:3000 | |
| Mon Aug 8 23:13:44 2016 at /tmp/ws line 6, <DATA> line 28. | |
| Mon Aug 8 23:13:45 2016 at /tmp/ws line 6, <DATA> line 28. | |
| Mon Aug 8 23:13:46 2016 at /tmp/ws line 6, <DATA> line 28. | |
| Mon Aug 8 23:13:47 2016 at /tmp/ws line 6, <DATA> line 28. | |
| Mon Aug 8 23:13:48 2016 at /tmp/ws line 6, <DATA> line 28. | |
| [Mon Aug 8 23:13:49 2016] [debug] GET "/" | |
| [Mon Aug 8 23:13:49 2016] [debug] Rendering template "index.html.ep" from DATA section | |
| [Mon Aug 8 23:13:49 2016] [debug] 200 OK (0.001603s, 623.830/s) | |
| [Mon Aug 8 23:13:49 2016] [debug] GET "/title" | |
| [Mon Aug 8 23:13:49 2016] [debug] Routing to a callback | |
| [Mon Aug 8 23:13:49 2016] [debug] 101 Switching Protocols (0.000304s, 3289.474/s) | |
| Mon Aug 8 23:13:49 2016 at /tmp/ws line 6, <DATA> line 28. | |
| Mon Aug 8 23:13:50 2016 at /tmp/ws line 6. | |
| Mon Aug 8 23:13:51 2016 at /tmp/ws line 6. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment