Snippets

Brian Medley yRa9x: Untitled snippet

Created by Brian Medley
use v5.10;

use Mojo::Base -strict;

use Mojo::UserAgent;
use Mojo::IOLoop;

# Open WebSocket to echo service
my $ua = Mojo::UserAgent->new;

$ua->websocket('ws://echo.websocket.org' => sub {
    my ($ua, $tx) = @_;
    
    # Check if WebSocket handshake was successful
    say 'WebSocket handshake failed!' and return unless $tx->is_websocket;

    my $id = Mojo::IOLoop->recurring(1 => sub {
        state $x = 1;

        $tx->send("Update: $x");
        
        $x++;

        $tx->finish if 7 == $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 necessary
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.