usev5.10;useMojo::Base-strict;useMojo::UserAgent;useMojo::IOLoop;# Open WebSocket to echo servicemy$ua=Mojo::UserAgent->new;$ua->websocket('ws://echo.websocket.org'=>sub{my($ua,$tx)=@_;# Check if WebSocket handshake was successfulsay'WebSocket handshake failed!'andreturnunless$tx->is_websocket;my$id=Mojo::IOLoop->recurring(1=>sub{state$x=1;$tx->send("Update: $x");$x++;$tx->finishif7==$x;});$tx->on(finish=>sub{my($tx,$code,$reason)=@_;say"WebSocket closed with status $code.";Mojo::IOLoop->remove($id);});$tx->on(message=>sub{my($tx,$msg)=@_;$DB::single=1;say"WebSocket message: $msg";});# Send a message to the server$tx->send('Hi!');});# Start event loop if necessaryMojo::IOLoop->startunlessMojo::IOLoop->is_running;
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.