newnew() starts a server based on POE::Component::Server::TCP and returns a session ID for the master
listening session. All error handling is done within the server, via the "Error" and "ClientError"
callbacks.
The server may be shut down by posting a "shutdown" event to the master session, either by its ID or the
name given to it by the "Alias" parameter.
POE::Component::Server::TCP does a lot of work in its constructor. The design goal is to push as much
overhead into one-time construction so that ongoing run-time has less overhead. Because of this, the
server's constructor can take quite a daunting number of parameters.
POE::Component::Server::TCP always returns a POE::Session ID for the session that will be listening for
new connections.
Many of the constructor parameters have been previously described. They are covered briefly again below.
ServerSessionConfiguration
These constructor parameters affect POE::Component::Server::TCP's main listening session.
Acceptor
"Acceptor" defines a CODE reference that POE::Wheel::SocketFactory's "SuccessEvent" will trigger to
handle new connections. Therefore the parameters passed to "Acceptor" are identical to those given to
"SuccessEvent".
"Acceptor" is optional; the default handler will create a new session for each connection. All the
"Client" constructor parameters are used to customize this session. In other words, "ClientInput" and
such arenotusedwhen"Acceptor"isset.
The default "Acceptor" adds significant convenience and flexibility to POE::Component::Server::TCP, but
it's not always a good fit for every application. In some cases, a custom "Acceptor" or even rolling
one's own server with POE::Wheel::SocketFactory and POE::Wheel::ReadWrite may be better and/or faster.
Acceptor => sub {
my ($socket, $remote_address, $remote_port) = @_[ARG0..ARG2];
# Set up something to interact with the client.
}
Address
"Address" defines a single interface address the server will bind to. It defaults to INADDR_ANY or
INADDR6_ANY, when using IPv4 or IPv6, respectively. It is often used with "Port".
The value in "Address" is passed to POE::Wheel::SocketFactory's "BindAddress" parameter, so it may be in
whatever form that module supports. At the time of this writing, that may be a dotted IPv4 quad, an IPv6
address, a host name, or a packed Internet address. See also "Hostname".
Address => '127.0.0.1' # Localhost IPv4
Address => "::1" # Localhost IPv6
Alias
"Alias" is an optional name that will be given to the server's master listening session. Events sent to
this name will not be delivered to individual connections.
The server's "Alias" may be important if it's necessary to shut a server down.
sub sigusr1_handler {
$_[KERNEL]->post(chargen_server => 'shutdown');
$_[KERNEL]->sig_handled();
}
Concurrency
"Concurrency" controls how many connections may be active at the same time. It defaults to -1, which
allows POE::Component::Server::TCP to accept concurrent connections until the process runs out of
resources.
Setting "Concurrency" to 0 prevents the server from accepting new connections. This may be useful if a
server must perform lengthy initialization before allowing connections. When the initialization
finishes, it can yield(set_concurrency => -1) to enable connections. Likewise, a running server may
yield(set_concurrency => 0) or any other number to dynamically tune its concurrency. See "EVENTS" for
more about the set_concurrency event.
Note: For "Concurrency" to work with a custom "Acceptor", the server's listening session must receive a
"disconnected" event whenever clients disconnect. Otherwise the listener cannot mediate between its
connections.
Example:
Acceptor => sub {
# ....
POE::Session->create(
# ....
inline_states => {
_start => sub {
# ....
# remember who our parent is
$_[HEAP]->{server_tcp} = $_[SENDER]->ID;
# ....
},
got_client_disconnect => sub {
# ....
$_[KERNEL]->post( $_[HEAP]->{server_tcp} => 'disconnected' );
# ....
}
}
);
}
Domain
"Domain" sets the address or protocol family within which to operate. The "Domain" may be any value that
POE::Wheel::SocketFactory supports. AF_INET (Internet address space) is used by default.
Use AF_INET6 for IPv6 support. This constant is exported by Socket or Socket6, depending on your version
of Perl. Also be sure to have Socket::GetAddrInfo installed, which is required by
POE::Wheel::SocketFactory for IPv6 support.
Error
"Error" is the callback that will be invoked when the server socket reports an error. The Error callback
will be used to handle POE::Wheel::SocketFactory's FailureEvent, so it will receive the same parameters
as discussed there.
A default error handler will be provided if Error is omitted. The default handler will log the error to
STDERR and shut down the server. Active connections will be permitted to complete their transactions.
Error => sub {
my ($syscall_name, $err_num, $err_str) = @_[ARG0..ARG2];
# Handle the error.
}
Hostname
"Hostname" is the optional non-packed name of the interface the TCP server will bind to. The hostname
will always be resolved via inet_aton() and so can either be a dotted quad or a name. Name resolution is
a one-time start-up action; there are no ongoing run-time penalties for using it.
"Hostname" guarantees name resolution, where "Address" does not. It's therefore preferred to use
"Hostname" in cases where resolution must always be done.
InlineStates
"InlineStates" is optional. If specified, it must hold a hashref of named callbacks. Its syntax is that
of POE:Session->create()'s inline_states parameter.
Remember: These InlineStates handlers will be added to the client sessions, not to the main listening
session. A yield() in the listener will not reach these handlers.
If POE::Kernel::ASSERT_USAGE is enabled, the constructor will croak() if it detects a state that it uses
internally. For example, please use the "Started" and "Stopped" callbacks if you want to specify your own
"_start" and "_stop" events respectively.
ObjectStates
If "ObjectStates" is specified, it must holde an arrayref of objects and the events they will handle.
The arrayref must follow the syntax for POE::Session->create()'s object_states parameter.
Remember: These ObjectStates handlers will be added to the client sessions, not to the main listening
session. A yield() in the listener will not reach these handlers.
If POE::Kernel::ASSERT_USAGE is enabled, the constructor will croak() if it detects a state that it uses
internally. For example, please use the "Started" and "Stopped" callbacks if you want to specify your own
"_start" and "_stop" events respectively.
PackageStates
When the optional "PackageStates" is set, it must hold an arrayref of package names and the events they
will handle The arrayref must follow the syntax for POE::Session->create()'s package_states parameter.
Remember: These PackageStates handlers will be added to the client sessions, not to the main listening
session. A yield() in the listener will not reach these handlers.
If POE::Kernel::ASSERT_USAGE is enabled, the constructor will croak() if it detects a state that it uses
internally. For example, please use the "Started" and "Stopped" callbacks if you want to specify your own
"_start" and "_stop" events respectively.
Port
"Port" contains the port the listening socket will be bound to. It defaults to 0, which usually lets the
operating system pick a port at random.
Port => 30023
It is often used with "Address".
Started
"Started" sets an optional callback that will be invoked within the main server session's context. It
notifies the server that it has fully started. The callback's parameters are the usual for a session's
_start handler.
Stopped
"Stopped" sets an optional callback that will be invoked within the main server session's context. It
notifies the server that it has fully stopped. The callback's parameters are the usual for a session's
_stop handler.
ListenerArgs
"ListenerArgs" is passed to the listener session as the "args" parameter. In other words, it must be an
arrayref, and the values are passed into the "Started" handler as ARG0, ARG1, etc.
ConnectionSessionConfiguration
These constructor parameters affect the individual sessions that interact with established connections.
ClientArgs
"ClientArgs" is optional. When specified, it holds an ARRAYREF that will be expanded one level and
passed to the "ClientConnected" callback in @_[ARG0..$#_].
ClientConnected
Each new client connection is handled by a new POE::Session instance. "ClientConnected" is a callback
that notifies the application when a client's session is started and ready for operation. Banners are
often sent to the remote client from this callback.
The @_[ARG0..$#_] parameters to "ClientConnected" are a copy of the values in the "ClientArgs"
constructor parameter's array reference. The other @_ members are standard for a POE::Session _start
handler.
"ClientConnected" is called once per session start-up. It will never be called twice for the same
connection.
ClientConnected => sub {
$_[HEAP]{client}->put("Hello, client!");
# Other client initialization here.
},
ClientDisconnected
"ClientDisconnected" is a callback that will be invoked when the client disconnects or has been
disconnected by the server. It's useful for cleaning up global client information, such as chat room
structures. "ClientDisconnected" callbacks receive the usual POE parameters, but nothing special is
included.
ClientDisconnected => sub {
warn "Client disconnected"; # log it
}
ClientError
The "ClientError" callback is invoked when a client socket reports an error. "ClientError" is called
with POE's usual parameters, plus the common error parameters: $_[ARG0] describes what was happening at
the time of failure. $_[ARG1] and $_[ARG2] contain the numeric and string versions of $!, respectively.
"ClientError" is optional. If omitted, POE::Component::Server::TCP will provide a default callback that
logs most errors to STDERR.
If "ClientShutdownOnError" is set, the connection will be shut down after "ClientError" returns. If
"ClientDisconnected" is specified, it will be called as the client session is cleaned up.
"ClientError" is triggered by POE::Wheel::ReadWrite's ErrorEvent, so it follows that event's form.
Please see the ErrorEvent documentation in POE::Wheel::ReadWrite for more details.
ClientError => sub {
my ($syscall_name, $error_num, $error_str) = @_[ARG0..ARG2];
# Handle the client error here.
}
ClientFilter
"ClientFilter" specifies the POE::Filter object or class that will parse input from each client and
serialize output before it's sent to each client.
"ClientFilter" may be a SCALAR, in which case it should name the POE::Filter class to use. Each new
connection will be given a freshly instantiated filter of that class. No constructor parameters will be
passed.
ClientFilter => "POE::Filter::Stream",
Some filters require constructor parameters. These may be specified by an ARRAYREF. The first element
is the POE::Filter class name, and subsequent elements are passed to the class' constructor.
ClientFilter => [ "POE::Filter::Line", Literal => "\n" ],
"ClientFilter" may also be given an archetypical POE::Filter OBJECT. In this case, each new client
session will receive a clone() of the given object.
ClientFilter => POE::Filter::Line->new(Literal => "\n"),
"ClientFilter" is optional. The component will use "POE::Filter::Line" if it is omitted. There is
"ClientInputFilter" and "ClientOutputFilter" if you want to specify a different filter for both
directions.
Filter modules are not automatically loaded. Be sure that the program loads the class before using it.
ClientFlushed
"ClientFlushed" exposes POE::Wheel::ReadWrite's "FlushedEvent" as a callback. It is called whenever the
client's output buffer has been fully flushed to the client socket. At this point it's safe to shut down
the socket without losing data.
"ClientFlushed" is useful for streaming servers, where a "flushed" event signals the need to send more
data.
ClientFlushed => sub {
my $data_source = $_[HEAP]{file_handle};
my $read_count = sysread($data_source, my $buffer = "", 65536);
if ($read_count) {
$_[HEAP]{client}->put($buffer);
}
else {
$_[KERNEL]->yield("shutdown");
}
},
POE::Component::Server::TCP's default "Acceptor" ensures that data is flushed before finishing a client
shutdown.
ClientInput
"ClientInput" defines a per-connection callback to handle client input. This callback receives its
parameters directly from POE::Wheel::ReadWrite's "InputEvent". ARG0 contains the input record, the
format of which is defined by "ClientFilter" or "ClientInputFilter". ARG1 has the wheel's unique ID, and
so on. Please see POE:Wheel::ReadWrite for an in-depth description of "InputEvent".
"ClientInput" and "Acceptor" are mutually exclusive. Enabling one prohibits the other.
ClientInput => sub {
my $input = $_[ARG0];
$_[HEAP]{wheel}->put("You said: $input");
},
ClientInputFilter
"ClientInputFilter" is used with "ClientOutputFilter" to specify different protocols for input and
output. Both must be used together. Both follow the same usage as "ClientFilter". Overrides the filter
set by "ClientFilter".
ClientInputFilter => [ "POE::Filter::Line", Literal => "\n" ],
ClientOutputFilter => 'POE::Filter::Stream',
ClientOutputFilter
"ClientOutputFilter" is used with "ClientInputFilter" to specify different protocols for input and
output. Both must be used together. Both follow the same usage as "ClientFilter". Overrides the filter
set by "ClientFilter".
ClientInputFilter => POE::Filter::Line->new(Literal => "\n"),
ClientOutputFilter => 'POE::Filter::Stream',
ClientShutdownOnError
"ClientShutdownOnError" tells the component whether client connections should be shut down automatically
if an error is detected. It defaults to "true". Setting it to false (0, undef, "") turns off this
feature.
The application is responsible for dealing with client errors if this feature is disabled. Not doing so
may cause the component to emit a constant stream of errors, eventually bogging down the application with
dead connections that spin out of control.
Yes, this is terrible. You have been warned.
SessionParams
"SessionParams" specifies additional parameters that will be passed to the "SessionType" constructor at
creation time. It must be an array reference.
SessionParams => [ options => { debug => 1, trace => 1 } ],
Note: POE::Component::Server::TCP supplies its own POE::Session constructor parameters. Conflicts
between them and "SessionParams" may cause the component to behave erratically. To avoid such problems,
please limit SessionParams to the "options" hash. See POE::Session for an known options.
We may enable other options later. Please let us know if you need something.
SessionType
"SessionType" specifies the POE::Session subclass that will be created for each new client connection.
"POE::Session" is the default.
SessionType => "POE::Session::MultiDispatch"