Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

How to use AnyEvent::Handle to read data from a websocket?

by pudda (Acolyte)
on Sep 29, 2020 at 12:41 UTC ( [id://11122327]=perlquestion: print w/replies, xml ) Need Help??

pudda has asked for the wisdom of the Perl Monks concerning the following question:

Hi!

I'm new with perl, so please have patience if I misunderstood anything, or got something wrong.

What I'm trying to do is connect to a websocket, read the data the ws is sending and do some stuff with it. My code is connecting to the ws but when I try to read and print in the console the data readed it shows nothing. Can you guys help me?

here's my code:

#!/usr/bin/env perl use strict; use warnings; use lib 'lib'; use Data::Dumper; use AnyEvent; use AnyEvent::Socket; use AnyEvent::Handle; $|++; my $cv = AnyEvent->condvar; my $ws_handle; $ws_handle = AnyEvent::Handle->new( connect => [ 'localhost', '8082' ], keepalive => 1, on_eof => sub { print ("! Server disconnected"); }, on_read => sub { my ($handle) = @_; my $buf = delete $handle->{rbuf}; print "teste"; }, on_connect => sub { my ($handle, $host, $port, $retry) = @_; print "Server connected\n"; # this works }, on_connect_error => sub { my ($handle, $message) = @_; print $message; }, ); $cv->recv;

Replies are listed 'Best First'.
Re: How to use AnyEvent::Handle to read data from a websocket?
by Corion (Patriarch) on Sep 29, 2020 at 13:24 UTC

      Wow thanks a lot!

      I rewrote my code using AnyEvent::WebSocket::Client and it is working just the way I wanted!

      Here's my code after changing it in case someone get curious:

      #!/usr/bin/env perl use strict; use warnings; use lib 'lib'; use Data::Dumper; use AnyEvent::WebSocket::Client 0.12; $|++; my $client = AnyEvent::WebSocket::Client->new; $client->connect("ws://localhost:8082/")->cb(sub { our $connection = eval { shift->recv }; if($@) { # handle error... warn $@; return; } $connection->send('a message'); $connection->on(each_message => sub { my($connection, $message) = @_; if($message->is_text || $message->is_binary) { my $body = $message->body; print $body. "\n"; } }); $connection->on(finish => sub { my($connection) = @_; print "Server Disconnected!\n" }); }); AnyEvent->condvar->recv;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11122327]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-04-25 23:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found