1IO::Multiplex(3) User Contributed Perl Documentation IO::Multiplex(3)
2
3
4
6 IO::Multiplex - Manage IO on many file handles
7
9 use IO::Multiplex;
10
11 my $mux = new IO::Multiplex;
12 $mux->add($fh1);
13 $mux->add(\*FH2);
14 $mux->set_callback_object(...);
15 $mux->listen($server_socket);
16 $mux->loop;
17
18 sub mux_input { ... }
19
20 "IO::Multiplex" is designed to take the effort out of managing multiple
21 file handles. It is essentially a really fancy front end to the
22 "select" system call. In addition to maintaining the "select" loop, it
23 buffers all input and output to/from the file handles. It can also
24 accept incoming connections on one or more listen sockets.
25
27 It is object oriented in design, and will notify you of significant
28 events by calling methods on an object that you supply. If you are not
29 using objects, you can simply supply "__PACKAGE__" instead of an object
30 reference.
31
32 You may have one callback object registered for each file handle, or
33 one global one. Possibly both -- the per-file handle callback object
34 will be used instead of the global one.
35
36 Each file handle may also have a timer associated with it. A callback
37 function is called when the timer expires.
38
39 Handling input on descriptors
40 When input arrives on a file handle, the "mux_input" method is called
41 on the appropriate callback object. This method is passed three
42 arguments (in addition to the object reference itself of course):
43
44 1. a reference to the mux,
45
46 2. A reference to the file handle, and
47
48 3. a reference to the input buffer for the file handle.
49
50 The method should remove the data that it has consumed from the
51 reference supplied. It may leave unconsumed data in the input buffer.
52
53 Handling output to descriptors
54 If "IO::Multiplex" did not handle output to the file handles as well as
55 input from them, then there is a chance that the program could block
56 while attempting to write. If you let the multiplexer buffer the
57 output, it will write the data only when the file handle is capable of
58 receiveing it.
59
60 The basic method for handing output to the multiplexer is the "write"
61 method, which simply takes a file descriptor and the data to be
62 written, like this:
63
64 $mux->write($fh, "Some data");
65
66 For convenience, when the file handle is "add"ed to the multiplexer, it
67 is tied to a special class which intercepts all attempts to write to
68 the file handle. Thus, you can use print and printf to send output to
69 the handle in a normal manner:
70
71 printf $fh "%s%d%X", $foo, $bar, $baz
72
73 Unfortunately, Perl support for tied file handles is incomplete, and
74 functions such as "send" cannot be supported.
75
76 Also, file handle object methods such as the "send" method of
77 "IO::Socket" cannot be intercepted.
78
80 Simple Example
81 This is a simple telnet-like program, which demonstrates the concepts
82 covered so far. It does not really work too well against a telnet
83 server, but it does OK against the sample server presented further
84 down.
85
86 use IO::Socket;
87 use IO::Multiplex;
88
89 # Create a multiplex object
90 my $mux = new IO::Multiplex;
91 # Connect to the host/port specified on the command line,
92 # or localhost:23
93 my $sock = new IO::Socket::INET(Proto => 'tcp',
94 PeerAddr => shift || 'localhost',
95 PeerPort => shift || 23)
96 or die "socket: $@";
97
98 # add the relevant file handles to the mux
99 $mux->add($sock);
100 $mux->add(\*STDIN);
101 # We want to buffer output to the terminal. This prevents the program
102 # from blocking if the user hits CTRL-S for example.
103 $mux->add(\*STDOUT);
104
105 # We're not object oriented, so just request callbacks to the
106 # current package
107 $mux->set_callback_object(__PACKAGE__);
108
109 # Enter the main mux loop.
110 $mux->loop;
111
112 # mux_input is called when input is available on one of
113 # the descriptors.
114 sub mux_input {
115 my $package = shift;
116 my $mux = shift;
117 my $fh = shift;
118 my $input = shift;
119
120 # Figure out whence the input came, and send it on to the
121 # other place.
122 if ($fh == $sock) {
123 print STDOUT $$input;
124 } else {
125 print $sock $$input;
126 }
127 # Remove the input from the input buffer.
128 $$input = '';
129 }
130
131 # This gets called if the other end closes the connection.
132 sub mux_close {
133 print STDERR "Connection Closed\n";
134 exit;
135 }
136
137 A server example
138 Servers are just as simple to write. We just register a listen socket
139 with the multiplex object "listen" method. It will automatically
140 accept connections on it and add them to its list of active file
141 handles.
142
143 This example is a simple chat server.
144
145 use IO::Socket;
146 use IO::Multiplex;
147
148 my $mux = new IO::Multiplex;
149
150 # Create a listening socket
151 my $sock = new IO::Socket::INET(Proto => 'tcp',
152 LocalPort => shift || 2300,
153 Listen => 4)
154 or die "socket: $@";
155
156 # We use the listen method instead of the add method.
157 $mux->listen($sock);
158
159 $mux->set_callback_object(__PACKAGE__);
160 $mux->loop;
161
162 sub mux_input {
163 my $package = shift;
164 my $mux = shift;
165 my $fh = shift;
166 my $input = shift;
167
168 # The handles method returns a list of references to handles which
169 # we have registered, except for listen sockets.
170 foreach $c ($mux->handles) {
171 print $c $$input;
172 }
173 $$input = '';
174 }
175
176 A more complex server example
177 Let us take a look at the beginnings of a multi-user game server. We
178 will have a Player object for each player.
179
180 # Paste the above example in here, up to but not including the
181 # mux_input subroutine.
182
183 # mux_connection is called when a new connection is accepted.
184 sub mux_connection {
185 my $package = shift;
186 my $mux = shift;
187 my $fh = shift;
188
189 # Construct a new player object
190 Player->new($mux, $fh);
191 }
192
193 package Player;
194
195 my %players = ();
196
197 sub new {
198 my $package = shift;
199 my $self = bless { mux => shift,
200 fh => shift } => $package;
201
202 # Register the new player object as the callback specifically for
203 # this file handle.
204
205 $self->{mux}->set_callback_object($self, $self->{fh});
206 print $self->{fh}
207 "Greetings, Professor. Would you like to play a game?\n";
208
209 # Register this player object in the main list of players
210 $players{$self} = $self;
211 $mux->set_timeout($self->{fh}, 1);
212 }
213
214 sub players { return values %players; }
215
216 sub mux_input {
217 my $self = shift;
218 shift; shift; # These two args are boring
219 my $input = shift; # Scalar reference to the input
220
221 # Process each line in the input, leaving partial lines
222 # in the input buffer
223 while ($$input =~ s/^(.*?)\n//) {
224 $self->process_command($1);
225 }
226 }
227
228 sub mux_close {
229 my $self = shift;
230
231 # Player disconnected;
232 # [Notify other players or something...]
233 delete $players{$self};
234 }
235 # This gets called every second to update player info, etc...
236 sub mux_timeout {
237 my $self = shift;
238 my $mux = shift;
239
240 $self->heartbeat;
241 $mux->set_timeout($self->{fh}, 1);
242 }
243
245 new
246 Construct a new "IO::Multiplex" object.
247
248 $mux = new IO::Multiplex;
249
250 listen
251 Add a socket to be listened on. The socket should have had the "bind"
252 and "listen" system calls already applied to it. The "IO::Socket"
253 module will do this for you.
254
255 $socket = new IO::Socket::INET(Listen => ..., LocalAddr => ...);
256 $mux->listen($socket);
257
258 Connections will be automatically accepted and "add"ed to the multiplex
259 object. "The mux_connection" callback method will also be called.
260
261 add
262 Add a file handle to the multiplexer.
263
264 $mux->add($fh);
265
266 As a side effect, this sets non-blocking mode on the handle, and
267 disables STDIO buffering. It also ties it to intercept output to the
268 handle.
269
270 remove
271 Removes a file handle from the multiplexer. This also unties the
272 handle. It does not currently turn STDIO buffering back on, or turn
273 off non-blocking mode.
274
275 $mux->remove($fh);
276
277 set_callback_object
278 Set the object on which callbacks are made. If you are not using
279 objects, you can specify the name of the package into which the method
280 calls are to be made.
281
282 If a file handle is supplied, the callback object is specific for that
283 handle:
284
285 $mux->set_callback_object($object, $fh);
286
287 Otherwise, it is considered a default callback object, and is used when
288 events occur on a file handle that does not have its own callback
289 object.
290
291 $mux->set_callback_object(__PACKAGE__);
292
293 The previously registered object (if any) is returned.
294
295 See also the CALLBACK INTERFACE section.
296
297 kill_output
298 Remove any pending output on a file descriptor.
299
300 $mux->kill_output($fh);
301
302 outbuffer
303 Return or set the output buffer for a descriptor
304
305 $output = $mux->outbuffer($fh);
306 $mux->outbuffer($fh, $output);
307
308 inbuffer
309 Return or set the input buffer for a descriptor
310
311 $input = $mux->inbuffer($fh);
312 $mux->inbuffer($fh, $input);
313
314 set_timeout
315 Set the timer for a file handle. The timeout value is a certain number
316 of seconds in the future, after which the "mux_timeout" callback is
317 called.
318
319 If the "Time::HiRes" module is installed, the timers may be specified
320 in fractions of a second.
321
322 Timers are not reset automatically.
323
324 $mux->set_timeout($fh, 23.6);
325
326 Use "$mux->set_timeout($fh, undef)" to cancel a timer.
327
328 handles
329 Returns a list of handles that the "IO::Multiplex" object knows about,
330 excluding listen sockets.
331
332 @handles = $mux->handles;
333
334 loop
335 Enter the main loop and start processing IO events.
336
337 $mux->loop;
338
339 endloop
340 Prematurly terminate the loop. The loop will automatically terminate
341 when there are no remaining descriptors to be watched.
342
343 $mux->endloop;
344
345 udp_peer
346 Get peer endpoint of where the last udp packet originated.
347
348 $saddr = $mux->udp_peer($fh);
349
350 is_udp
351 Sometimes UDP packets require special attention. This method will tell
352 if a file handle is of type UDP.
353
354 $is_udp = $mux->is_udp($fh);
355
356 write
357 Send output to a file handle.
358
359 $mux->write($fh, "'ere I am, JH!\n");
360
361 shutdown
362 Shut down a socket for reading or writing or both. See the "shutdown"
363 Perl documentation for further details.
364
365 If the shutdown is for reading, it happens immediately. However,
366 shutdowns for writing are delayed until any pending output has been
367 successfully written to the socket.
368
369 $mux->shutdown($socket, 1);
370
371 close
372 Close a handle. Always use this method to close a handle that is being
373 watched by the multiplexer.
374
375 $mux->close($fh);
376
378 Callback objects should support the following interface. You do not
379 have to provide all of these methods, just provide the ones you are
380 interested in.
381
382 All methods receive a reference to the callback object (or package) as
383 their first argument, in the traditional object oriented way.
384 References to the "IO::Multiplex" object and the relevant file handle
385 are also provided. This will be assumed in the method descriptions.
386
387 mux_input
388 Called when input is ready on a descriptor. It is passed a reference
389 to the input buffer. It should remove any input that it has consumed,
390 and leave any partially received data in the buffer.
391
392 sub mux_input {
393 my $self = shift;
394 my $mux = shift;
395 my $fh = shift;
396 my $data = shift;
397
398 # Process each line in the input, leaving partial lines
399 # in the input buffer
400 while ($$data =~ s/^(.*?\n)//) {
401 $self->process_command($1);
402 }
403 }
404
405 mux_eof
406 This is called when an end-of-file condition is present on the
407 descriptor. This is does not nessecarily mean that the descriptor has
408 been closed, as the other end of a socket could have used "shutdown" to
409 close just half of the socket, leaving us free to write data back down
410 the still open half. Like mux_input, it is also passed a reference to
411 the input buffer. It should consume the entire buffer or else it will
412 just be lost.
413
414 In this example, we send a final reply to the other end of the socket,
415 and then shut it down for writing. Since it is also shut down for
416 reading (implicly by the EOF condition), it will be closed once the
417 output has been sent, after which the mux_close callback will be
418 called.
419
420 sub mux_eof {
421 my $self = shift;
422 my $mux = shift;
423 my $fh = shift;
424
425 print $fh "Well, goodbye then!\n";
426 $mux->shutdown($fh, 1);
427 }
428
429 mux_close
430 Called when a handle has been completely closed. At the time that
431 "mux_close" is called, the handle will have been removed from the
432 multiplexer, and untied.
433
434 mux_outbuffer_empty
435 Called after all pending output has been written to the file
436 descriptor.
437
438 mux_connection
439 Called upon a new connection being accepted on a listen socket.
440
441 mux_timeout
442 Called when a timer expires.
443
445 Copyright 1999 Bruce J Keeler <bruce@gridpoint.com>
446
447 Copyright 2001-2008 Rob Brown <bbb@cpan.org>
448
449 Released under the same terms as Perl itself.
450
451 $Id: Multiplex.pm,v 1.45 2015/04/09 21:27:54 rob Exp $
452
453
454
455perl v5.38.0 2023-07-20 IO::Multiplex(3)