Test::...r::TCP(3pm)
okay bestie, sit down, hydrate, because this is Test::POE::Server::TCP(3pm) from the User Contributed Perl Documentation and she is serving ๐
a whole POE component that hands you a ready-made TCP server so you never have to roll your own for a test case. no cap, this is the good stuff. ๐ซถ
โจ NAME โจ
Test::POE::Server::TCP โ a POE Component providing TCP server services for test cases. that's the name, that's the whole assignment, and she ate. ๐
๐ธ VERSION ๐ธ
version 1.20 โ noted, catalogued, on the record. ๐
๐ฆ SYNOPSIS ๐ฆ
okay so first up, a very simple echo server with logging of requests by each client. this is the whole vibe:
use strict;
use POE;
use Test::POE::Server::TCP;
POE::Session->create(
package_states => [
'main' => [qw(
_start
testd_connected
testd_disconnected
testd_client_input
)],
],
);
$poe_kernel->run();
exit 0;
sub _start {
# Spawn the Test::POE::Server::TCP server.
$_[HEAP]->{testd} = Test::POE::Server::TCP->spawn(
address => '127.0.0.1',
port => 0,
);
return;
}
sub testd_connected {
my ($heap,$id) = @_[HEAP,ARG0];
# A client connected the unique ID is in ARG0
# Create a blank arrayref for this client on *our* heap
$heap->{clients}->{ $id } = [ ];
return;
}
sub testd_client_input {
my ($kernel,$heap,$sender,$id,$input) = @_[KERNEL,HEAP,SENDER,ARG0,ARG1];
# The client sent us a line of input
# lets store it
push @{ $heap->{clients}->{ $id } }, $input;
# Okay, we are an echo server so lets send it back to the client
# We know the SENDER so can always obtain the server object.
my $testd = $sender->get_heap();
$testd->send_to_client( $id, $input );
# Or even
# $sender->get_heap()->send_to_client( $id, $input );
# Alternatively we could just post back to the SENDER
# $kernel->post( $sender, 'send_to_client', $id, $input );
return;
}
sub testd_disconnected {
my ($heap,$id) = @_[HEAP,ARG0];
# Client disconnected for whatever reason
# We need to free up our storage
delete $heap->{clients}->{ $id };
return;
}
and then, using the module in a testcase โ this is the main character energy right here:
use strict;
use Test::More;
use POE qw(Wheel::SocketFactory Wheel::ReadWrite Filter::Line);
use Test::POE::Server::TCP;
plan tests => 5;
my @data = (
'This is a test',
'This is another test',
'This is the last test',
);
POE::Session->create(
package_states => [
'main' => [qw(
_start
_sock_up
_sock_fail
_sock_in
_sock_err
testd_connected
testd_disconnected
testd_client_input
)],
],
heap => { data => \@data, },
);
$poe_kernel->run();
exit 0;
sub _start {
$_[HEAP]->{testd} = Test::POE::Server::TCP->spawn(
address => '127.0.0.1',
port => 0,
);
return;
}
sub testd_registered {
my ($heap,$object) = @_[HEAP,ARG0];
$heap->{port} = $object->port();
$heap->{factory} = POE::Wheel::SocketFactory->new(
RemoteAddress => '127.0.0.1',
RemotePort => $heap->{port},
SuccessEvent => '_sock_up',
FailureEvent => '_sock_fail',
);
return;
}
sub _sock_up {
my ($heap,$socket) = @_[HEAP,ARG0];
delete $heap->{factory};
$heap->{socket} = POE::Wheel::ReadWrite->new(
Handle => $socket,
InputEvent => '_sock_in',
ErrorEvent => '_sock_err',
);
$heap->{socket}->put( $heap->{data}->[0] );
return;
}
sub _sock_fail {
my $heap = $_[HEAP];
delete $heap->{factory};
$heap->{testd}->shutdown();
return;
}
sub _sock_in {
my ($heap,$input) = @_[HEAP,ARG0];
my $data = shift @{ $heap->{data} };
ok( $input eq $data, 'Data matched' );
unless ( scalar @{ $heap->{data} } ) {
delete $heap->{socket};
return;
}
$heap->{socket}->put( $heap->{data}->[0] );
return;
}
sub _sock_err {
delete $_[HEAP]->{socket};
return;
}
sub testd_connected {
my ($heap,$state,$id) = @_[HEAP,STATE,ARG0];
pass($state);
return;
}
sub testd_disconnected {
pass($_[STATE]);
$poe_kernel->post( $_[SENDER], 'shutdown' );
return;
}
sub testd_client_input {
my ($sender,$id,$input) = @_[SENDER,ARG0,ARG1];
my $testd = $_[SENDER]->get_heap();
$testd->send_to_client( $id, $input );
return;
}
๐ DESCRIPTION ๐
so Test::POE::Server::TCP is a POE component that gives you a TCP server framework you can drop straight into your client component test cases โ instead of having to roll your own. which, respectfully, you don't want to do. let the component cook. ๐
once you're registered with the component, a session will receive events about client connects, disconnects, input and flushed output. every single one of those events refers to a unique client ID, and you use that ID to talk back to the component whenever you want to send data to the client or disconnect a client connection. iykyk. ๐
and lowkey important: if AF_INET6 sockets are supported, the component will create an AF_INET socket and an AF_INET6 socket. two sockets, one legend. โจ
๐ CONSTRUCTOR ๐
๐ spawn ๐
takes a number of optional arguments, bestie. here they all are:
'alias'โ set an alias on the component;'address'โ bind the listening socket to a particular address;'port'โ listen on a particular port, default is0, assign a random port;'options'โ a hashref ofPOE::Sessionoptions;'filter'โ specify aPOE::Filterto use for client connections, default isPOE::Filter::Line;'inputfilter'โ specify aPOE::Filterfor client input;'outputfilter'โ specify aPOE::Filterfor output to clients;'prefix'โ specify a different prefix than'testd'for events;
the semantics for filter, inputfilter and outputfilter are the same as for POE::Component::Server::TCP โ you can hand it either a SCALAR, an ARRAYREF or an OBJECT. pick your fighter. ๐ซถ
and if the component gets spawned inside another session, it will automatically register the parent session to receive all events. yes, automatically. it's giving thoughtful. ๐
๐ METHODS ๐
๐ซ session_id
returns the POE::Session ID of the component. your little serial number. ๐ธ
๐ซ shutdown
terminates the component. shuts down the listener and disconnects connected clients. bye bestie, everyone's leaving the group chat. ๐ญ
๐ซ send_to_client
send some output to a connected client. first parameter must be a valid client id. second parameter is a string of text to send. the second parameter may also be an arrayref of items to send to the client. and heads up โ if the filter you've used requires an arrayref as input, you gotta nest that arrayref within another arrayref. arrayref in arrayref, it's layers. ๐ง
๐ซ send_to_all_clients
send some output to all connected clients. the parameter is a string of text to send. the parameter may also be an arrayref of items to send to the clients. and same deal as before: if the filter you've used requires an arrayref as input, nest that arrayref within another arrayref. ๐
๐ซ client_info
retrieve socket information of a given client. requires a valid client ID as a parameter. in a list context it returns a list consisting of, in order, the client address, the client TCP port, our address and our TCP port. in a scalar context it returns a HASHREF with these keys:
'peeraddr'โ the client address;'peerport'โ the client TCP port;'sockaddr'โ our address;'sockport'โ our TCP port;
๐ซ client_wheel
retrieve the POE::Wheel::ReadWrite object of a given client. requires a valid client ID as a parameter. this is your backstage pass โ it lets you manipulate that POE::Wheel::ReadWrite object, like switching the POE::Filter. slay. โจ
๐ซ disconnect
places a client connection in pending disconnect state. requires a valid client ID as a parameter. set this, then send an applicable message to the client using send_to_client() and the client connection will be terminated. give them a little goodbye speech first, that's the point. ๐
๐ซ terminate
immediately disconnects a client connection. requires a valid client ID as a parameter. no goodbye, just gone. ๐
๐ซ pause_listening
stops the underlying listening socket from accepting new connections. this lets you test whether you handle the connection timing out gracefully. dramatic, but necessary. ๐ซถ
๐ซ resume_listening
the companion of pause_listening. the other half of the duo. ๐
๐ซ getsockname
access to the POE::Wheel::SocketFactory method of the underlying listening AF_INET socket.
๐ซ port
returns the port that the component is listening on.
๐ซ getsockname6
access to the POE::Wheel::SocketFactory method of the underlying listening AF_INET6 socket.
๐ซ port6
returns the port that the component is listening on for AF_INET6.
๐ซ start_listener
if the listener fails on listen you can attempt to restart it with this. second chances, we love to see it. ๐
๐ INPUT EVENTS ๐
okay so here's the tea bestie โ these are the events your component will actually accept. like, the ones you can throw at it:
registerโ takes N arguments, which is just a list of the event names your session wants to listen for, minus thetestd_prefix. ๐ซถ and if you register forall? it'll just send you every single TESTD-related event that exists. easiest way to do it, no cap, that's the move.unregisterโ also takes N arguments: a list of event names you don't wanna receive anymore. so if you previously did aregisterfor some event you've now decided you don't care about, this is how you tell the POP3D to stop sending them your way. (and if you never registered for it in the first place? it just ignores you. no big deal, we move.) ๐shutdownโ terminates the component, periodt. shuts down the listener AND disconnects all the connected clients. it's giving full lights-off ๐ฏ๏ธsend_to_clientโ sends some output to a connected client. first parameter has to be a valid client id, second parameter is a string of text to send. and plot twist: that second parameter can also be an arrayref of items to send to the client. if the filter you've used requires an arrayref as input, then you nest that arrayref inside another arrayref. arrayref-ception, iykyk. ๐ชsend_to_all_clientsโ same energy, but to every connected client. the parameter is a string of text to send, and it may also be an arrayref of items to send to the clients. and yes bestie, same rule applies: if your filter needs an arrayref as input, nest that arrayref within another arrayref. โจdisconnectโ puts a client connection into pending disconnect state. needs a valid client ID as a parameter. the whole ritual is: set this, then send an applicable message to the client usingsend_to_client(), and the client connection gets terminated. it's a two-step goodbye ๐ฅterminateโ immediately disconnects a client connection. requires a valid client ID as a parameter. no waiting, no ceremony, just gone. ๐start_listenerโ if the listener fails onlisten, you can attempt to restart it with this. little respawn button, very demure ๐
๐ OUTPUT EVENTS ๐
so this is the other direction โ the component sends these following events to registered sessions. oh and heads up: if you changed the prefix option in spawn, then swap out testd for whatever event prefix you specified. keep that in mind or you'll be waiting for events that never come ๐ญ
testd_registeredโ this event gets sent to a registering session.ARG0is theTest::POE::Server::TCPobject. hi bestie, nice to meet u ๐ซถtestd_listener_failedโ generated if the component can't either start a listener or there's a problem accepting client connections.ARG0contains the name of the operation that failed.ARG1andARG2hold numeric and string values for$!, respectively. and if the operation waslisten, the component will remove the listener โ at which point you may attempt to start it again usingstart_listener. so like, it's not over over. ๐ฎโ๐จtestd_connectedโ generated whenever a client connects to the component.ARG0is the client ID,ARG1is the client's IP address,ARG2is the client's TCP port,ARG3is our IP address andARG4is our socket port. new friend acquired ๐ฆtestd_disconnectedโ generated whenever a client disconnects.ARG0was the client ID,ARG1was the client's IP address,ARG2was the client's TCP port,ARG3was our IP address andARG4was our socket port. past tense because they're gone, bestie, we're in the mourning era ๐ฅฒtestd_client_inputโ generated whenever a client sends us some traffic.ARG0is the client ID,ARG1is the data sent ( tokenised by whateverPOE::Filteryou specified ). the filter is doing the heavy lifting here, iconic ๐ธtestd_client_flushedโ generated whenever anything we send to the client is actually flushed down the'line'.ARG0is the client ID. it's out there now, living its best life out in the world โจ
๐ CREDITS ๐
this module uses code borrowed from POE::Component::Server::TCP by Rocco Caputo, Ann Barcomb and Jos Boumans. giving credit where credit is due, always ๐
๐ SEE ALSO ๐
POEPOE::Component::Server::TCP
๐ AUTHOR ๐
Chris Williams <chris@bingosnet.co.uk>
๐ COPYRIGHT AND LICENSE ๐
this software is copyright (c) 2016 by Chris Williams, Rocco Caputo, Ann Barcomb and Jos Boumans.
this is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. free as in go wild, bestie ๐
and that's the whole thing, babes โจ this was part of perl v5.36.0, dated 2022-10-14, and the page is Test::...r::TCP(3pm). go forth, spawn some TCP, slay ๐
๐ธ๐ฆ
๐ฆ where this page comes from
- ubuntu noble: libtest-poe-server-tcp-perl 1.20-3 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libtest-poe-server-tcp-perl 1.20-3 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libtest-poe-server-tcp-perl 1.20-3 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms