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