1POE::Component::Client:U:sTeCrP(C3o)ntributed Perl DocumPeOnEt:a:tCioomnponent::Client::TCP(3)
2
3
4
6 POE::Component::Client::TCP - a simplified TCP client
7
9 #!perl
10
11 use warnings;
12 use strict;
13
14 use POE qw(Component::Client::TCP);
15
16 POE::Component::Client::TCP->new(
17 RemoteAddress => "yahoo.com",
18 RemotePort => 80,
19 Connected => sub {
20 $_[HEAP]{server}->put("HEAD /");
21 },
22 ServerInput => sub {
23 my $input = $_[ARG0];
24 print "from server: $input\n";
25 },
26 );
27
28 POE::Kernel->run();
29 exit;
30
32 POE::Component::Client::TCP implements a generic single-Session client.
33 Internally it uses POE::Wheel::SocketFactory to establish the
34 connection and POE::Wheel::ReadWrite to interact with the server.
35
36 POE::Component::Client::TCP is customized by providing callbacks for
37 common operations. Most operations have sensible default callbacks, so
38 clients may be created with as little work as possible.
39
40 Performance Considerations
41 POE::Component::Client::TCP's ease of use comes at a price. The
42 component is generic, so it's not tuned to perform well for any
43 particular application.
44
45 If performance is your primary goal, POE::Kernel's select_read() and
46 select_write() perform about the same as IO::Select, but your code will
47 be portable across every event loop POE supports.
48
50 new
51 new() starts a client based on POE::Component::Client::TCP and returns
52 the ID of the session that will handle server interaction.
53
54 new() returns immediately, which may be before the client has
55 established its connection. It is always reliable to wait for the
56 "Connected" callback to fire before transmitting data to the server.
57
58 The client's constructor may seem to take a daunting number of
59 parameters. As with most POE modules, POE::Component::Client::TCP
60 tries to do as much work in its constructor so that the run-time code
61 path is relatively light.
62
63 Constructor Parameters Affecting the Session
64
65 The parameters in this section affect how the client's POE::Session
66 object will be created.
67
68 Alias
69
70 "Alias" is an optional symbolic name for the client's Session. It
71 allows other sessions to post events to the client, such as "shutdown"
72 and "reconnect". The client itself may yield() these events, so an
73 alias isn't usually needed.
74
75 Alias => "client",
76
77 Args
78
79 "Args" is optional. When specified, it holds an ARRAYREF that will be
80 passed to the "Started" callback via @_[ARG0..$#_]. This allows a
81 program to pass extra information into the client session.
82
83 InlineStates
84
85 "InlineStates" is optional. If specified, it must hold a hashref of
86 named callbacks. Its syntax is that of POE:Session->create()'s
87 inline_states parameter.
88
89 ObjectStates
90
91 If "ObjectStates" is specified, it must hold an arrayref of objects and
92 the events they will handle. The arrayref must follow the syntax for
93 POE::Session->create()'s object_states parameter.
94
95 PackageStates
96
97 When the optional "PackageStates" is set, it must hold an arrayref of
98 package names and the events they will handle The arrayref must follow
99 the syntax for POE::Session->create()'s package_states parameter.
100
101 PreConnect
102
103 "PreConnect" is called before "Connected", and it has different
104 parameters: $_[ARG0] contains a copy of the socket before it's given to
105 POE::Wheel::ReadWrite for management. Most HEAP members are set,
106 except of course $_[HEAP]{server}, because the POE::Wheel::ReadWrite
107 object has not been created yet. "PreConnect" may enable SSL on the
108 socket using POE::Component::SSLify. "PreConnect" must return a valid
109 socket to complete the connection; the client will disconnect if
110 anything else is returned.
111
112 PreConnect => {
113 # Convert the socket into an SSL socket.
114 my $socket = eval { Client_SSLify($_[ARG0]) };
115
116 # Disconnect if SSL failed.
117 return if $@;
118
119 # Return the SSL-ified socket.
120 return $socket;
121 }
122
123 SessionType
124
125 Each client is created within its own Session. "SessionType" names the
126 class that will be used to create the session.
127
128 SessionType => "POE::Session::MultiDispatch",
129
130 "SessionType" is optional. The component will use "POE::Session" by
131 default.
132
133 SessionParams
134
135 "SessionParams" specifies additional parameters that will be passed to
136 the "SessionType" constructor at creation time. It must be an array
137 reference.
138
139 SessionParams => [ options => { debug => 1, trace => 1 } ],
140
141 Note: POE::Component::Client::TCP supplies its own POE::Session
142 constructor parameters. Conflicts between them and "SessionParams" may
143 cause the component to behave erratically. To avoid such problems,
144 please limit SessionParams to the "options" hash. See POE::Session for
145 an known options.
146
147 We may enable other options later. Please let us know if you need
148 something.
149
150 Started
151
152 "Started" sets an optional callback that will be invoked within the
153 client session has been started. The callback's parameters are the
154 usual for the session's _start handler.
155
156 "Args" may be used to pass additional parameters to "Started". This
157 can be used to bypass issues introduced by closures. The values from
158 "Args" will be included in the @_[ARG0..$#_] parameters.
159
160 sub handle_started {
161 my @args = @_[ARG0..$#_];
162 # ...
163 }
164
165 POE::Wheel::SocketFactory Constructor Parameters
166
167 The constructor parameters in this section affect how the client's
168 POE::Wheel::SocketFactory object will be created.
169
170 BindAddress
171
172 "BindAddress" specifies the local interface address to bind to before
173 starting to connect. This allows the client to connect from a specific
174 address when multiple interfaces are available.
175
176 "BindAddress" is optional. If specified, its value will be passed
177 directly to POE::Wheel::SocketFactory's BindAddress constructor
178 parameter.
179
180 BindPort
181
182 "BindPort" sets the local socket port that the client will be bound to
183 before starting to connect. This allows the client to connect from a
184 specific port.
185
186 It's not usually necessary to bind to a particular port, so "BindPort"
187 is optional and disabled by default.
188
189 If specified, the value in "BindPort" is passed directly to
190 POE::Wheel::SocketFactory's own BindPort constructor parameter.
191
192 ConnectError
193
194 "ConnectError" is an optional callback to handle errors from
195 POE::Wheel::SocketFactory. These errors happen when a socket can't be
196 created or has trouble connecting to the remote host.
197
198 The following parameters will be passed to the callback along with the
199 usual POE event parameters: $_[ARG0] will describe what was happening
200 at the time of failure. $_[ARG1] and $_[ARG2] will contain the numeric
201 and string versions of $!, respectively.
202
203 Depending on the nature of the error and the type of client, it may be
204 useful to reconnect from the ConnectError callback.
205
206 ConnectError => sub {
207 my ($operation, $error_number, $error_string) = @_[ARG0..ARG2];
208 warn "$operation error $error_number occurred: $error_string";
209 if (error_is_recoverable($error_number)) {
210 $_[KERNEL]->delay( reconnect => 60 );
211 }
212 else {
213 $_[KERNEL]->yield("shutdown");
214 }
215 },
216
217 POE::Component::Client::TCP will shut down after ConnectError if a
218 reconnect isn't requested.
219
220 Connected
221
222 Connections are asynchronously set up and may take some time to
223 complete. "Connected" is an optional callback that notifies a program
224 when the connection has finally been made.
225
226 This is an advisory callback that occurs after a POE::Wheel::ReadWrite
227 object has already been created. Programs should not need to create
228 their own.
229
230 "Connected" is called in response to POE::Wheel::SocketFactory's
231 SuccessEvent. In addition to the usual POE event parameters, it
232 includes a copy of the established socket handle in $_[ARG0].
233 POE::Component::Client::TCP will manage the socket, so an application
234 should rarely need to save a copy of it. $_[ARG1] and $_[ARG2] contain
235 the remote address and port as returned from getpeername().
236
237 Connected => {
238 my ($socket, $peer_addr, $peer_port) = @_[ARG0, ARG1, ARG2];
239 # ...
240 }
241
242 See "PreConnect" to modify the socket before it's given to
243 POE::Wheel::ReadWrite.
244
245 ConnectTimeout
246
247 "ConnectTimeout" is the maximum number of seconds to wait for a
248 connection to be established. If it is omitted, Client::TCP relies on
249 the operating system to abort stalled connect() calls.
250
251 The application will be notified of a timeout via the ConnectError
252 callback. In the case of a timeout, $_[ARG0] will contain "connect",
253 and $_[ARG1] and $_[ARG2] will contain the numeric and string
254 representations of the ETIMEDOUT error.
255
256 Domain
257
258 "Domain" sets the address or protocol family within which to operate.
259 The "Domain" may be any value that POE::Wheel::SocketFactory supports.
260 AF_INET (Internet address space) is used by default.
261
262 Use AF_INET6 for IPv6 support. This constant is exported by Socket.
263 Also be sure to have Socket::GetAddrInfo installed, which is required
264 by POE::Wheel::SocketFactory for IPv6 support.
265
266 RemoteAddress
267
268 "RemoteAddress" contains the address of the server to connect to. It
269 is required and may contain a host name ("poe.perl.org"), a dot- or
270 colon-separated numeric address (depending on the Domain), or a packed
271 socket address. Pretty much anything POE::Wheel::SocketFactory's
272 RemoteAddress parameter does.
273
274 RemotePort
275
276 "RemotePort" contains the port of the server to connect to. It is
277 required and may be a service name ("echo") or number (7).
278
279 POE::Wheel::ReadWrite Constructor Parameters
280
281 Parameters in this section control configuration of the client's
282 POE::Wheel::ReadWrite object.
283
284 Disconnected
285
286 "Disconnected" is an optional callback to notify a program that an
287 established socket has been disconnected. It includes no special
288 parameters.
289
290 It may be useful to reconnect from the Disconnected callback, in the
291 case of MUD bots or long-running services. For example:
292
293 Disconnected => sub {
294 $_[KERNEL]->delay( reconnect => 60 );
295 },
296
297 The component will shut down if the connection ceases without being
298 reconnected.
299
300 Filter
301
302 "Filter" specifies the type of POE::Filter object that will parse input
303 from and serialize output to a server. It may either be a scalar, an
304 array reference, or a POE::Filter object.
305
306 If "Filter" is a scalar, it will be expected to contain a POE::Filter
307 class name:
308
309 Filter => "POE::Filter::Line",
310
311 "Filter" is optional. In most cases, the default "POE::Filter::Line"
312 is fine.
313
314 If "Filter" is an array reference, the first item in the array will be
315 treated as a POE::Filter class name. The remaining items will be
316 passed to the filter's constructor. In this example, the vertical bar
317 will be used as POE::Filter::Line's record terminator:
318
319 Filter => [ "POE::Filter::Line", Literal => "|" ],
320
321 If it is an object, it will be cloned every time the client connects:
322
323 Filter => POE::Filter::Line->new(Literal => "|"),
324
325 Be sure to "use" the appropriate POE::Filter subclass when specifying a
326 "Filter" other than the default.
327
328 ServerError
329
330 "ServerError" is an optional callback that will be invoked when an
331 established server connection has encountered some kind of error. It
332 is triggered by POE::Wheel::ReadWrite's ErrorEvent. By default, the
333 component will log any errors to STDERR. This may be suppressed by
334 defining a quieter ServerError callback.
335
336 As with "ConnectError", it is invoked with the customary error
337 parameters: $_[ARG0] will contain the name of the operation that
338 failed. $_[ARG1] and $_[ARG2] will hold the numeric and string forms
339 of $!, respectively.
340
341 Components usually disconnect on error. POE::Component::Client::TCP
342 will shut down if the socket disconnects without being reconnected.
343
344 ServerFlushed
345
346 "ServerFlushed" is an optional callback to notify a program that
347 ReadWrite's output buffers have completely flushed. It has no special
348 parameters.
349
350 The component will shut down after a server flush if $heap->{shutdown}
351 is set.
352
353 ServerInput
354
355 "ServerInput" is a required callback. It is called for each fully
356 parsed input record received by POE::Wheel::ReadWrite. $_[ARG0]
357 contains the input record, the format of which is determined by the
358 "Filter" constructor parameter.
359
360 "SeverInput" will stop being called when $_[HEAP]{shutdown} is true.
361 The most reliable way to set the "shutdown" member is to call
362 $_[KERNEL]->yield("shutdown").
363
365 POE::Component::Client::TCP handles a small number of public "command"
366 messages. These may be posted into the client from an external
367 session, or yielded from within the client.
368
369 connect
370 The "connect" event causes POE::Component::Client::TCP to begin
371 connecting to a server. It optionally includes a new RemoteHost and
372 RemotePort, both of which will be used for subsequent reconnections.
373
374 $_[KERNEL]->post(alias => connect => "127.0.0.1", 80);
375
376 If the client is already connected to a server, it will disconnect
377 immediately before beginning the new connection procedure. Buffered
378 input and output will be lost.
379
380 reconnect
381 The "reconnect" command causes POE::Component::Client::TCP to
382 immediately disconnect its current connection and begin reconnecting to
383 its most recently set RemoteHost and RemotePort. Any buffered input
384 and output will be lost.
385
386 shutdown
387 The "shutdown" command tells POE::Component::Client::TCP to flush its
388 buffers, disconnect, and begin DESTROY procedures.
389
390 All input will be discarded after receipt of "shutdown". All pending
391 output will be written to the server socket before disconnecting and
392 destructing.
393
395 POE::Component::Client::TCP requires some heap space for its own
396 bookkeeping. The following members are used and should be used as
397 directed, or with care.
398
399 This sample input handler is an example of most reserved heap members:
400
401 sub handle_input {
402 # Pending input from when we were connected.
403 return unless $_[HEAP]{connected};
404
405 # We've been shut down.
406 return if $_[HEAP]{shutdown};
407
408 my $input = $_[ARG0];
409 $_[HEAP]{server}->put("you sent: $input");
410 }
411
412 server
413 The read-only "server" heap member contains the POE::Wheel object used
414 to connect to or talk with the server. While the component is
415 connecting, "server" will be a POE::Wheel::SocketFactory object. After
416 the connection has been made, "server" is replaced with a
417 POE::Wheel::ReadWrite object.
418
419 The most reliable way to avoid prematurely using "server" is to first
420 check the "connected" reserved heap member. See the example above.
421
422 shutdown
423 "shutdown" is a read-only flag that tells the component it's shutting
424 down. It should only be by the "shutdown" event, which does other
425 cleanup.
426
427 "shutdown" may be checked to avoid starting new work during a client's
428 shutting-down procedure. See the example above.
429
430 connected
431 "connected" is a read-only flag that indicates whether the component is
432 currently connected.
433
434 shutdown_on_error
435 "shutdown_on_error" is a read-only flag that governs the component's
436 shutdown-on-error behavior. When true, POE::Component::Client::TCP
437 will automatically shutdown when it encounters an error.
438
440 The SEE ALSO section in POE contains a table of contents covering the
441 entire POE distribution.
442
443 POE::Component::Server::TCP is the server-side counterpart to this
444 module.
445
446 This component uses and exposes features from POE::Filter,
447 POE::Wheel::SocketFactory, and POE::Wheel::ReadWrite.
448
449 See "SYNOPSIS" in POE::Wheel::SocketFactory for a more efficient but
450 lower-level way to create clients and servers.
451
453 This looks nothing like what Ann envisioned.
454
455 POE::Component::Client::TCP is a generic client. As such, it's not
456 tuned for any particular task. While it handles the common cases well
457 and with a minimum of code, it may not be suitable for everything.
458
460 POE::Component::Client::TCP is Copyright 2001-2013 by Rocco Caputo.
461 All rights are reserved. POE::Component::Client::TCP is free software,
462 and it may be redistributed and/or modified under the same terms as
463 Perl itself.
464
465 POE::Component::Client::TCP is based on code, used with permission,
466 from Ann Barcomb <kudra@domaintje.com>.
467
468 POE::Component::Client::TCP is based on code, used with permission,
469 from Jos Boumans <kane@cpan.org>.
470
471
472
473perl v5.32.0 2020-07-28 POE::Component::Client::TCP(3)