AnyEve...:Server(3pm)

πŸ“¦ version 0.10, in opensuse-leap 16.0

πŸŽ€ NAME πŸŽ€

  • AnyEvent::WebSocket::Server β€” WebSocket server for AnyEvent πŸ‘‘βœ¨

okay so this is the AnyEvent::WebSocket::Server page, bestie β€” the manual header lowkey labels it AnyEve...:Server(3pm) and it’s from the User Contributed Perl Documentation. Let’s get into it πŸ’…πŸ¦‹


✨ SYNOPSIS ✨

Here’s the whole vibe, no cap:

use AnyEvent::Socket qw(tcp_server);
use AnyEvent::WebSocket::Server;

my $server = AnyEvent::WebSocket::Server->new();

my $tcp_server;
$tcp_server = tcp_server undef, 8080, sub {
    my ($fh) = @_;
    $server->establish($fh)->cb(sub {
        my $connection = eval { shift->recv };
        if($@) {
            warn "Invalid connection request: $@\n";
            close($fh);
            return;
        }
        $connection->on(each_message => sub {
            my ($connection, $message) = @_;
            $connection->send($message); ## echo
        });
        $connection->on(finish => sub {
            undef $connection;
        });
    });
};

πŸ’– DESCRIPTION πŸ’–

This class is literally an implementation of the WebSocket server in an AnyEvent context, bestie. Main character server energy 🫢


🌸 CLASS METHODS 🌸

🧚 $server = AnyEvent::WebSocket::Server->new(%args)

The constructor. Iconic. ✨

Fields in %args are:

  • "handshake" => CODE (optional) β€” A subroutine reference to customize the WebSocket handshake process. You can use this option to validate and preprocess the handshake request and customize the handshake response. Obsessed πŸ’–

For each request, the handshake code is called like

($response, @other_results) = $handshake->($request, $default_response)

where $request is a Protocol::WebSocket::Request object, and $default_response is a Protocol::WebSocket::Response object. The $handshake code must return $response. @other_results are optional.

The return value $response is the handshake response returned to the client. It must be either a Protocol::WebSocket::Response object, or a string of a valid HTTP response (including the Status-Line, the Headers and the Body). No random vibes allowed in that response, bestie.

The argument $default_response is a Protocol::WebSocket::Response valid for the given $request. If you don’t need to manipulate the response, just return $default_response. That is,

handshake => sub { $_[1] }

is the minimal valid code for "handshake". Minimal queen behavior πŸŽ€

In addition to $response, you can return @other_results if you want. Those @other_results can be obtained later from the condition variable of establish() method.

If you throw an exception from $handshake code, the module treats it as a rejection of the $request. In this case, the condition variable of establish() method croaks. Drama, but make it error handling. 😭

  • "validator" => CODE (optional) β€” This option is only for backward compatibility. Use "handshake" option instead. If "handshake" option is specified, this option is ignored. iykyk πŸ’…

A subroutine reference to validate the incoming WebSocket request. If omitted, it accepts the request.

The validator is called like

@other_results = $validator->($request)

where $request is a Protocol::WebSocket::Request object.

If you reject the $request, throw an exception.

If you accept the $request, don’t throw any exception. The return values of the $validator are sent to the condition variable of establish() method.

  • "ssl_key_file" => FILE_PATH (optional) β€” A string of the filepath to the SSL/TLS private key file in PEM format. If you set this option, you have to set "ssl_cert_file" option, too. That’s a package deal, bestie.

If this option or "ssl_cert_file" option is set, AnyEvent::WebSocket::Server encrypts the WebSocket streams with SSL/TLS. Secure the bag πŸ”

  • "ssl_cert_file" => FILE_PATH (optional) β€” A string of the filepath to the SSL/TLS certificate file in PEM format.

The file may contain both the certificate and corresponding private key. In that case, "ssl_key_file" may be omitted. Convenient? We love.

If this option is set, AnyEvent::WebSocket::Server encrypts the WebSocket streams with SSL/TLS.

  • "max_payload_size" => INT (optional) β€” The maximum payload size for received frames. Currently defaults to whatever Protocol::WebSocket defaults to. Note that payload size for sent frames are not limited. Received frames said β€œrespect my limits”, sent frames said β€œno ❀️”.

πŸ¦‹ OBJECT METHODS πŸ¦‹

🧚 $conn_cv = $server->establish($fh)

Establish a WebSocket connection to a client via the given connection filehandle. Connection era ✨

$fh is a filehandle for a connection socket, which is usually obtained by tcp_server() function in AnyEvent::Socket.

Return value $conn_cv is an AnyEvent condition variable.

In success, "$conn_cv->recv" returns an AnyEvent::WebSocket::Connection object and @other_results returned by the handshake process. In failure (e.g. the client sent a totally invalid request or your handshake process threw an exception), $conn_cv will croak an error message. Not the slay outcome, but important. πŸ’€

($connection, @other_results) = eval { $conn_cv->recv };

## or in scalar context, it returns $connection only.
$connection = eval { $conn_cv->recv };

if($@) {
    my $error = $@;
    ...
    return;
}
do_something_with($connection);

You can use $connection to send and receive data through WebSocket. See AnyEvent::WebSocket::Connection for detail.

Note that even if $conn_cv croaks, the connection socket $fh remains intact. You can communicate with the client via $fh unless the client has already closed it. So don’t panic-close everything, bestie. 😭

🧚 $conn_cv = $server->establish_psgi($psgi_env, [$fh])

The same as establish() method except that the request is in the form of PSGI environment. PSGI girlies rise 🫢

$psgi_env is a PSGI environment object obtained from a PSGI server. $fh is the connection filehandle. If $fh is omitted, "$psgi_env->{"psgix.io"}" is used for the connection (see PSGI::Extensions).


🌈 EXAMPLES 🌈

πŸ’… handshake option

The following server accepts WebSocket URLs such as ws://localhost:8080/2013/10. Year and month parsing, we love to see it. ✨

use AnyEvent::Socket qw(tcp_server);
use AnyEvent::WebSocket::Server;

my $server = AnyEvent::WebSocket::Server->new(
    handshake => sub {
        my ($req, $res) = @_;
        ## $req is a Protocol::WebSocket::Request
        ## $res is a Protocol::WebSocket::Response

        ## validating and parsing request.
        my $path = $req->resource_name;
        die "Invalid format" if $path !~ m{^/(\d{4})/(\d{2})};

        my ($year, $month) = ($1, $2);
        die "Invalid month" if $month <= 0 || $month > 12;

        ## setting WebSocket subprotocol in response
        $res->subprotocol("mytest");

        return ($res, $year, $month);
    }
);

tcp_server undef, 8080, sub {
    my ($fh) = @_;
    $server->establish($fh)->cb(sub {
        my ($conn, $year, $month) = eval { shift->recv };
        if($@) {
            my $error = $@;
            error_response($fh, $error);
            return;
        }
        $conn->send("You are accessing YEAR = $year, MONTH = $month");
        $conn->on(finish => sub { undef $conn });
    });
};

πŸ‘‘ SEE ALSO πŸ‘‘

  • AnyEvent::WebSocket::Client β€” AnyEvent-based WebSocket client implementation. The matching icon πŸ’…
  • Net::WebSocket::Server β€” Minimalistic stand-alone WebSocket server. It uses its own event loop mechanism.
  • Net::Async::WebSocket β€” Stand-alone WebSocket server and client implementation using IO::Async

πŸ’… AUTHOR πŸ’…

Toshio Ito, "<toshioito at cpan.org>" author behavior πŸ‘‘

🫢 CONTRIBUTORS 🫢

  • mephinet (Philipp Gortan) ✨

⭐ REPOSITORY ⭐

The repo lives at https://github.com/debug-ito/AnyEvent-WebSocket-Server 🫢

πŸ”₯ ACKNOWLEDGEMENTS πŸ”₯

  • Graham Ollis (plicease) - author of AnyEvent::WebSocket::Client respect the ecosystem πŸŽ€

Copyright 2013 Toshio Ito.

This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.


okay that’s the whole page, bestie!! πŸ’– This version is from perl v5.42.0, dated 2021-01-25, and the footer also shows AnyEve...:Server(3pm) β€” now go be iconic with your WebSocket server βœ¨πŸ¦‹πŸŽ€

πŸ“¦ where this page comes from