DOKK / manpages / debian 12 / libmojolicious-perl / Mojo::WebSocket.3pm.en
Mojo::WebSocket(3pm) User Contributed Perl Documentation Mojo::WebSocket(3pm)

Mojo::WebSocket - The WebSocket protocol

  use Mojo::WebSocket qw(WS_TEXT build_frame parse_frame);
  my $bytes = build_frame 0, 1, 0, 0, 0, WS_TEXT, 'Hello World!';
  my $frame = parse_frame \$bytes, 262144;

Mojo::WebSocket implements the WebSocket protocol as described in RFC 6455 <https://tools.ietf.org/html/rfc6455>. Note that 64-bit frames require a Perl with support for quads or they are limited to 32-bit.

Mojo::WebSocket implements the following functions, which can be imported individually.

  my $bytes = build_frame $masked, $fin, $rsv1, $rsv2, $rsv3, $op, $payload;

Build WebSocket frame.

  # Masked binary frame with FIN bit and payload
  say build_frame 1, 1, 0, 0, 0, WS_BINARY, 'Hello World!';
  # Text frame with payload but without FIN bit
  say build_frame 0, 0, 0, 0, 0, WS_TEXT, 'Hello ';
  # Continuation frame with FIN bit and payload
  say build_frame 0, 1, 0, 0, 0, WS_CONTINUATION, 'World!';
  # Close frame with FIN bit and without payload
  say build_frame 0, 1, 0, 0, 0, WS_CLOSE, '';
  # Ping frame with FIN bit and payload
  say build_frame 0, 1, 0, 0, 0, WS_PING, 'Test 123';
  # Pong frame with FIN bit and payload
  say build_frame 0, 1, 0, 0, 0, WS_PONG, 'Test 123';

  my $bool = challenge Mojo::Transaction::WebSocket->new;

Check WebSocket handshake challenge.

  my $tx = client_handshake Mojo::Transaction::HTTP->new;

Perform WebSocket handshake client-side.

  my $frame = parse_frame \$bytes, $limit;

Parse WebSocket frame.

  # Parse single frame and remove it from buffer
  my $frame = parse_frame \$buffer, 262144;
  say "FIN: $frame->[0]";
  say "RSV1: $frame->[1]";
  say "RSV2: $frame->[2]";
  say "RSV3: $frame->[3]";
  say "Opcode: $frame->[4]";
  say "Payload: $frame->[5]";

  my $tx = server_handshake Mojo::Transaction::HTTP->new;

Perform WebSocket handshake server-side.

Mojo::WebSocket implements the following constants, which can be imported individually.

WS_BINARY

Opcode for "Binary" frames.

WS_CLOSE

Opcode for "Close" frames.

WS_CONTINUATION

Opcode for "Continuation" frames.

WS_PING

Opcode for "Ping" frames.

WS_PONG

Opcode for "Pong" frames.

WS_TEXT

Opcode for "Text" frames.

You can set the "MOJO_WEBSOCKET_DEBUG" environment variable to get some advanced diagnostics information printed to "STDERR".

  MOJO_WEBSOCKET_DEBUG=1

Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.

2022-12-22 perl v5.36.0