LoginSignup
4
6

More than 5 years have passed since last update.

コマンドラインでWebSocketクライアント

Last updated at Posted at 2015-08-29

Mojolicious - 5年前の動かなくなっていたWebSocketコードをなんとかする - Qiita
の続き。

curlコマンドみたいなhttpアクセスできるものを想像すると近い。
Webブラウザ使わなくてもデバッグできるので負荷試験だとかにも役立つ。

送信して切断

agent.pl
use strict;
use warnings;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;
$ua->websocket('ws://localhost/echo' => sub {
  my ($ua, $tx) = @_;
  print "WebSocket handshake failed!\n" and return unless $tx->is_websocket;

  $tx->on(finish => sub {
    my ($tx, $code, $reason) = @_;
    print "WebSocket closed with status $code.\n";
  });

  $tx->on(message => sub {
    my ($tx, $msg) = @_;
    print "WebSocket message: $msg\n";
    $tx->finish;
  });

  $tx->send('Hi!');
});
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
$ perl agent.pl
WebSocket message: {"hms":"23:58:05","text":"Hi!"}
WebSocket closed with status 1005.

待ち続けて受信する

loop.pl
use strict;
use warnings;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;
$ua->websocket('ws://localhost/echo' => sub {
  my ($ua, $tx) = @_;
  print "WebSocket handshake failed!\n" and return unless $tx->is_websocket;

  Mojo::IOLoop->stream($tx->connection)->timeout(0);

  $tx->on(finish => sub {
    my ($tx, $code, $reason) = @_;
    print "WebSocket closed with status $code.\n";
  });

  $tx->on(message => sub {
    my ($tx, $msg) = @_;
    print "WebSocket message: $msg\n";
    #$tx->finish;
  });

  $tx->send('Hi!');
});
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
$ perl loop.pl
WebSocket message: {"hms":"23:59:31","text":"Hi!"}
WebSocket message: {"hms":"23:59:34","text":"aaa"}
WebSocket message: {"hms":"23:59:36","text":"bbb"}
WebSocket message: {"hms":"23:59:37","text":"ccc"}
WebSocket message: {"hms":"23:59:42","text":"test"}

ブラウザから送信すると受信したメッセージが標準出力に出る

参考

Mojo::UserAgent · yuki-kimoto/mojolicious-guides-japanese Wiki
https://github.com/yuki-kimoto/mojolicious-guides-japanese/wiki/Mojo::UserAgent

Mojo::UserAgent - Non-blocking I/O HTTP and WebSocket user agent
http://mojolicio.us/perldoc/Mojo/UserAgent

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6