WebSocket::Client - WebSocket Client
use WebSocket::Client; use Term::Prompt; my $uri = "ws://localhost:8080?csrf=token"; my $ws; $ws = WebSocket::Client->new( $uri, { do_pong => sub{ $ws->pong }, on_binary => \&on_binary, on_connect => \&on_connect, on_disconnect => \&on_disconnect, on_error => \&on_error, on_handshake => \&on_handshake, on_ping => \&on_ping, on_pong => \&on_pong, on_recv => \&on_recv, on_send => \&on_send, on_utf8 => \&on_message, origin => 'http://localhost', debug => 3, version => 13, }) || die( WebSocket::Client->error ); $ws->connect() || die( $ws->error ); $SIG{INT} = $SIG{TERM} = sub { my( $sig ) = @_; $ws->disconnect if( $ws ); exit( $sig eq 'TERM' ? 0 : 1 ); }; while(1) { my $msg = prompt( 'x', "> ", 'type the message to send', '' ); next unless( $msg =~ /\S+/ ); $ws->send_utf8( $msg ) || die( $ws->error ); }
v0.1.1
This is the WebSocket client class. It contains all the methods and api to connect to a remote WebSocket server and interact with it.
The constructor takes an uri and the following options. If an uri is not provided as a first argument, it can be provided as a uri parameter; see below:
uri
compression_threshold
See "compression_threshold"
cookie
A Cookie http field header value. It must be properly formatted.
Cookie
do_pong
The code reference used to issue a pong. By default this is set to "pong"
pong
extensions
Optional. One or more extension enabled for this client. For example permessage-deflate to enable message compression.
permessage-deflate
You can set this to either a string or a WebSocket::Extension object if you want, for example to set the extension parameters.
See rfc6455 section 9.1 for more information on extension.
Seel also "compression_threshold".
max_fragments_amount
max_payload_size
on_binary
A code reference that will be triggered upon a binary message received from the server.
See "on_binary" for more details.
on_connect
A code reference that will be triggered upon successful connection to the remote WebSocket server, but before any handshake is performed.
See "on_connect" for more details.
on_disconnect
A code reference that will be triggered upon the closing of the connection with the server.
See "on_disconnect" for more details.
on_error
A code reference that will be triggered whenever an error is encountered upon parsing of the handshake.
See "on_error" for more details.
on_handshake
A code reference that will be triggered just before the handshake procedure is completed, but right after the handshake has been received from the server.
Be careful, the code reference must return true upon success, or else, it will trigger a handshake failure.
on_ping
A code reference that will be triggered when a ping is received from the WebSocket server.
ping
See "on_ping" for more details. and Mozilla documentation on ping and pong
See also "do_pong" to set the code reference to perform a pong
on_pong
A code reference that will be triggered when a pong is received from the WebSocket server, most likely as a reply to our initial ping.
See "on_pong" for more details. and Mozilla documentation on ping and pong
on_recv
A code reference that will be triggered whenever some text or binary payload data is received from the server.
See "on_recv" for more details.
on_send
A code reference that will be triggered whenever data is sent to the remote WebSocket server.
See "on_send" for more details.
on_utf8
A code reference that will be triggered whenever text message is sent to the remote WebSocket server.
See "on_utf8" for more details.
origin
The origin of the request. See rfc6455 section on opening handshake
subprotocol
An array reference of protocols. They can be arbitrary identifiers and they are optionals.
See rfc6455 section on subprotocol
This can be changed later with "subprotocol"
The uri for the remote WebSocket server.
version
The version of the WebSocket protocol. For example: draft-ietf-hybi-17
draft-ietf-hybi-17
Inherited from WebSocket
Set or get the threshold in bytes above which the ut8 or binary messages will be compressed if the client and the server support compression and it is activated as an extension.
Initiate the handshake with the server and return the current object.
Before returning, this method will fork a separate process to listen to incoming messages in the background, so as to be non-blocking and return control to the caller.
my $client = WebSocket::Client->new( 'wss://chat.example.org' )->connect || die( WebSocket::Client->error ); # Listener process runs now in the background $client->send( 'Hello !' );
Sets or gets the boolean value representing whether the client is currently connected to the remote WebSocket server.
Set or get the Cookie header value.
Returns a scalar object
Close the connection with the server, and return the current object.
Set or get a boolean value representing the connection status to the remote server socket.
There are 2 status: disconnecting and disconnected. The former is set when the client has issued a disconnection message to the remote server and is waiting for the server to acknowledge it, as per the WebSocket protocol, and the latter is set when the connection is effectively shut down.
disconnecting
disconnected
Set or get the boolean value indicating the state of connection to the remote server socket.
This is set to a true value when the client has issued a disconnection notification to the server and is awaiting a response from the server, as per the rfc6455 protocol
Set or get the code reference used to issue a pong. By default this is set to "pong"
Set or get the frame buffer object.
Set or get the handshake object
Set or get the ip of the remote server. This is set once a connection is established.
This method is called by "connect" to listen to incoming message from the server. It is actually called twice. Once during the handshake and once the handshake is completed, the client forks a separate process in which it calls this method to listen to incoming messages.
Takes an integer and set or get the maximum fragments amount.
Takes an integer and set or get the maximum payload size.
Provided with an array or array reference of event name and core reference pairs and this will set those event handlers.
It returns the current object.
Event handler triggered when a binary message is received.
The current client object and the binary message are passed as argument to the event handler.
Any fatal error occurring in the callback are caught using try-catch with (Nice::Try)
Event handler triggered when the connection with the server has been made and before any handshake has been performed.
The current client object is passed as argument to the event handler.
Any fatal error occurring in the callback are caught using try-catch with (Nice::Try), and if an error occurs, this method will set an error and return undef or an empty list depending on the context.
undef
Event handler triggered before the connection with the server is closed.
Any fatal error occurring in the callback are caught using try-catch with (Nice::Try), and if an error occurs, this method will raise a warning if warnings are enabled.
Event handler triggered whenever an error occurs upon parsing of the handshake.
The current client object and the error object are passed as argument to the event handler.
Event handler triggered just before the handshake sequence is completed, but right after the handshake has been received from the server.
Be careful that this must return a true value, or else, it will fail the handshake.
A code reference that will be triggered when a ping is received from the WebSocket server and right before a pong is sent back.
If the callback returns a defined, but false value, no pong will be issued in reply. A defined but false value could be an empty string or 0. This is designed in case when you do not waant to reply to the server's ping and thus inform it the client is still there.
0
It would probably be best to simply disconnect, but anyhow the feature is there.
See Mozilla documentation on ping and pong
See also "do_pong" to set the code reference to perform a pong in response.
The event handler is then passed the current client object.
See rfc6455 for more on this
Note that this handler is different from "do_pong", which is used to issue a pong back to the server in response to a ping received.
Event handler triggered whenever a binary or text payload is received from the server.
The current frame object and the payload data are passed as arguments to the event handler.
$ws->on_recv(sub { my( $frame, $payload ) = @_; if( $frame->is_binary ) { # do something } elsif( $frame->is_text ) { # do something else } });
Event handler triggered whenever a message is sent to the remote server.
The current client object and the message are passed as argument to the event handler.
This callback is triggered on two occasions:
In either case, fatal error occurring in the callback are caught using try-catch with (Nice::Try), and if an error occurs, this method will raise a warning if warnings are enabled.
Event handler triggered whenever a text message is sent to the remote server.
Set or get the origin of the request as a Module::Generic::Scalar object.
Send a ping to the WebSocket server and returns the value returned by "send". It passes "send" whatever extra argument was provided.
Send a pong to the WebSocket server and returns the value returned by "send". It passes "send" whatever extra argument was provided.
Will attempt to read data from the server socket and call all relevant event handlers. It returns the current object.
Sends data to the server socket and returns the current object. This will also trigger associated event handlers.
Returns the current object.
Sends binary data to the server socket and returns the current object. This will also trigger associated event handlers.
Sends data to the server socket after having encoded them using "encode" in Encode> and returns the current object. This will also trigger associated event handlers.
Start listening for possible events on the server socket.
Set or get an array object of WebSocket protocols and set the WebSocket header Sec-WebSocket-Protocol.
Sec-WebSocket-Protocol
Returns a Module::Generic::Array object.
See rfc6455 for more information
Shut down the socket by sending a "shutdown" in IO::Socket command and sets the "disconnected" status to true.
Set or get the remote server socket. This expects the object to be a IO::Socket instance, or an inheriting package.
Set or get the timeout used when issuing messages to the remote server, such as close and waiting for the server response.
close
Returns the uri of the server uri.
See rfc6455 specification
The WebSocket protocol version being used, such as draft-ietf-hybi-17
See rfc6455 about suport for multiple versions
Graham Ollis for AnyEvent::WebSocket::Client, Eric Wastl for Net::WebSocket::Server, Vyacheslav Tikhanovsky aka VTI for Protocol::WebSocket
Jacques Deguest <jack@deguest.jp>
WebSocket::Server, rfc6455
Copyright(c) 2021-2023 DEGUEST Pte. Ltd.
You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.
To install WebSocket, copy and paste the appropriate command in to your terminal.
cpanm
cpanm WebSocket
CPAN shell
perl -MCPAN -e shell install WebSocket
For more information on module installation, please visit the detailed CPAN module installation guide.