2 # This has been taken from the 'Advanced Perl Programming' book by Sriram Srinivasan
4 # I am presuming that the code is distributed on the same basis as perl itself.
6 # I have modified it to suit my devious purposes (Dirk Koopman G1TLH)
18 use vars qw(%rd_callbacks %wt_callbacks $rd_handles $wt_handles $now @timerchain %conns);
22 $rd_handles = IO::Select->new();
23 $wt_handles = IO::Select->new();
27 my $blocking_supported = 0;
30 # Checks if blocking is supported
32 require POSIX; POSIX->import(qw (F_SETFL O_NONBLOCK EAGAIN));
34 $blocking_supported = 1 unless $@;
38 #-----------------------------------------------------------------
39 # Generalised initializer
43 my ($pkg, $rproc) = @_;
45 my $class = $obj || $pkg;
57 return bless $conn, $class;
68 $call = $pkg->{call} unless $call;
69 return undef unless $call;
70 confess "changing $pkg->{call} to $call" if exists $pkg->{call} && $call ne $pkg->{call};
72 $ref = $conns{$call} = $pkg;
79 # this is only called by any dependent processes going away unexpectedly
84 my @pid = grep {$_->{pid} == $pid} values %conns;
87 &{$_->{rproc}}($_, undef, "$pid has gorn");
94 #-----------------------------------------------------------------
97 my ($pkg, $to_host, $to_port, $rproc) = @_;
99 # Create a connection end-point object
102 $conn = $pkg->new($rproc);
105 # Create a new internet socket
106 my $sock = IO::Socket::INET->new (
107 PeerAddr => $to_host,
108 PeerPort => $to_port,
111 Timeout => $conn->{timeval} / 2);
113 return undef unless $sock;
115 $conn->{sock} = $sock;
117 if ($conn->{rproc}) {
118 my $callback = sub {_rcv($conn)};
119 set_event_handler ($sock, "read" => $callback);
126 my $sock = delete $conn->{sock};
127 $conn->{state} = 'E';
129 $conn->{timeout}->del_timer if $conn->{timeout};
131 # be careful to delete the correct one
132 if (my $call = $conn->{call}) {
133 my $ref = $conns{$call};
134 delete $conns{$call} if $ref && $ref == $conn;
137 set_event_handler ($sock, "read" => undef, "write" => undef);
138 unless ($^O =~ /^MS/i) {
139 kill 'TERM', $conn->{pid} if exists $conn->{pid};
141 return unless defined($sock);
147 my ($conn, $msg) = @_;
148 $conn->enqueue($msg);
149 $conn->_send (1); # 1 ==> flush
153 my ($conn, $msg) = @_;
154 $conn->enqueue($msg);
155 my $sock = $conn->{sock};
156 return unless defined($sock);
157 set_event_handler ($sock, "write" => sub {$conn->_send(0)});
162 push (@{$conn->{outqueue}}, $_[0]);
166 my ($conn, $flush) = @_;
167 my $sock = $conn->{sock};
168 return unless defined($sock);
169 my $rq = $conn->{outqueue};
171 # If $flush is set, set the socket to blocking, and send all
172 # messages in the queue - return only if there's an error
173 # If $flush is 0 (deferred mode) make the socket non-blocking, and
174 # return to the event loop only after every message, or if it
175 # is likely to block in the middle of a message.
177 $flush ? $conn->set_blocking() : $conn->set_non_blocking();
178 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
182 my $mlth = length($msg);
183 my $bytes_to_write = $mlth - $offset;
184 my $bytes_written = 0;
185 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
186 while ($bytes_to_write > 0) {
187 $bytes_written = syswrite ($sock, $msg,
188 $bytes_to_write, $offset);
189 if (!defined($bytes_written)) {
190 if (_err_will_block($!)) {
191 # Should happen only in deferred mode. Record how
192 # much we have already sent.
193 $conn->{send_offset} = $offset;
194 # Event handler should already be set, so we will
195 # be called back eventually, and will resume sending
198 delete $conn->{send_offset};
199 $conn->handle_send_err($!);
201 return 0; # fail. Message remains in queue ..
204 $offset += $bytes_written;
205 $bytes_to_write -= $bytes_written;
207 delete $conn->{send_offset};
210 last unless $flush; # Go back to select and wait
211 # for it to fire again.
213 # Call me back if queue has not been drained.
215 set_event_handler ($sock, "write" => sub {$conn->_send(0)});
217 set_event_handler ($sock, "write" => undef);
222 sub _err_will_block {
223 if ($blocking_supported) {
224 return ($_[0] == EAGAIN());
228 sub set_non_blocking { # $conn->set_blocking
229 if ($blocking_supported) {
230 # preserve other fcntl flags
231 my $flags = fcntl ($_[0], F_GETFL(), 0);
232 fcntl ($_[0], F_SETFL(), $flags | O_NONBLOCK());
236 if ($blocking_supported) {
237 my $flags = fcntl ($_[0], F_GETFL(), 0);
238 $flags &= ~O_NONBLOCK(); # Clear blocking, but preserve other flags
239 fcntl ($_[0], F_SETFL(), $flags);
243 sub handle_send_err {
244 # For more meaningful handling of send errors, subclass Msg and
246 my ($conn, $err_msg) = @_;
247 warn "Error while sending: $err_msg \n";
248 set_event_handler ($conn->{sock}, "write" => undef);
251 #-----------------------------------------------------------------
252 # Receive side routines
255 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
256 my ($pkg, $my_host, $my_port, $login_proc) = @_;
257 my $self = $pkg->new($login_proc);
259 $self->{sock} = IO::Socket::INET->new (
260 LocalAddr => $my_host,
261 LocalPort => $my_port,
265 die "Could not create socket: $! \n" unless $self->{sock};
266 set_event_handler ($self->{sock}, "read" => sub { $self->new_client } );
275 while ($msg = shift @{$conn->{inqueue}}){
276 &{$conn->{rproc}}($conn, $msg, $!);
281 sub _rcv { # Complement to _send
282 my $conn = shift; # $rcv_now complement of $flush
283 # Find out how much has already been received, if at all
284 my ($msg, $offset, $bytes_to_read, $bytes_read);
285 my $sock = $conn->{sock};
286 return unless defined($sock);
289 $conn->set_non_blocking();
290 $bytes_read = sysread ($sock, $msg, 1024, 0);
291 if (defined ($bytes_read)) {
292 if ($bytes_read > 0) {
294 @lines = split /\r?\n/, $msg;
296 $lines[0] = $conn->{msg} . $lines[0] if exists $conn->{msg};
298 $lines[0] = $conn->{msg} if exists $conn->{msg};
299 push @lines, '' unless @lines;
304 $conn->{msg} = pop @lines;
306 push @{$conn->{inqueue}}, @lines if @lines;
308 $conn->{msg} .= $msg;
312 if (_err_will_block($!)) {
320 if (defined $bytes_read && $bytes_read == 0) {
321 # $conn->disconnect();
322 &{$conn->{rproc}}($conn, undef, $!);
323 delete $conn->{inqueue};
330 my $server_conn = shift;
331 my $sock = $server_conn->{sock}->accept();
332 my $conn = $server_conn->new($server_conn->{rproc});
333 $conn->{sock} = $sock;
334 my $rproc = &{$server_conn->{rproc}} ($conn, $sock->peerhost(), $sock->peerport());
336 $conn->{rproc} = $rproc;
337 my $callback = sub {_rcv($conn)};
338 set_event_handler ($sock, "read" => $callback);
339 } else { # Login failed
347 set_event_handler ($conn->{sock}, "read" => undef);
348 $conn->{sock}->close;
351 #----------------------------------------------------
352 # Event loop routines used by both client and server
354 sub set_event_handler {
355 shift unless ref($_[0]); # shift if first arg is package name
356 my ($handle, %args) = @_;
358 if (exists $args{'write'}) {
359 $callback = $args{'write'};
361 $wt_callbacks{$handle} = $callback;
362 $wt_handles->add($handle);
364 delete $wt_callbacks{$handle};
365 $wt_handles->remove($handle);
368 if (exists $args{'read'}) {
369 $callback = $args{'read'};
371 $rd_callbacks{$handle} = $callback;
372 $rd_handles->add($handle);
374 delete $rd_callbacks{$handle};
375 $rd_handles->remove($handle);
382 my ($pkg, $time, $proc, $recur) = @_;
384 my $class = $obj || $pkg;
385 my $self = bless { t=>$time + time, proc=>$proc }, $class;
386 $self->{interval} = $time if $recur;
387 push @timerchain, $self;
394 @timerchain = grep {$_ != $self} @timerchain;
398 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
399 my ($conn, $r, $w, $rset, $wset);
402 # Quit the loop if no handles left to process
403 last unless ($rd_handles->count() || $wt_handles->count());
406 IO::Select->select ($rd_handles, $wt_handles, undef, $timeout);
409 foreach $r (@$rset) {
410 &{$rd_callbacks{$r}} ($r) if exists $rd_callbacks{$r};
412 foreach $w (@$wset) {
413 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
416 # handle things on the timer chain
418 if ($now >= $_->{t}) {
420 $_->{t} = $now + $_->{interval} if exists $_->{interval};
425 @timerchain = grep { $_->{t} > $now } @timerchain;
427 if (defined($loop_count)) {
428 last unless --$loop_count;