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);
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;
56 return bless $conn, $class;
59 #-----------------------------------------------------------------
62 my ($pkg, $to_host, $to_port, $rproc) = @_;
64 # Create a new internet socket
65 my $sock = IO::Socket::INET->new (
71 return undef unless $sock;
73 # Create a connection end-point object
76 $conn = $pkg->new($rproc);
78 $conn->{sock} = $sock;
81 my $callback = sub {_rcv($conn)};
82 set_event_handler ($sock, "read" => $callback);
89 my $sock = delete $conn->{sock};
92 $conn->{timeout}->del_timer if $conn->{timeout};
93 return unless defined($sock);
94 set_event_handler ($sock, "read" => undef, "write" => undef);
100 my ($conn, $msg) = @_;
101 $conn->enqueue($msg);
102 $conn->_send (1); # 1 ==> flush
106 my ($conn, $msg) = @_;
107 $conn->enqueue($msg);
108 my $sock = $conn->{sock};
109 return unless defined($sock);
110 set_event_handler ($sock, "write" => sub {$conn->_send(0)});
115 push (@{$conn->{outqueue}}, $_[0]);
119 my ($conn, $flush) = @_;
120 my $sock = $conn->{sock};
121 return unless defined($sock);
122 my $rq = $conn->{outqueue};
124 # If $flush is set, set the socket to blocking, and send all
125 # messages in the queue - return only if there's an error
126 # If $flush is 0 (deferred mode) make the socket non-blocking, and
127 # return to the event loop only after every message, or if it
128 # is likely to block in the middle of a message.
130 $flush ? $conn->set_blocking() : $conn->set_non_blocking();
131 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
135 my $mlth = length($msg);
136 my $bytes_to_write = $mlth - $offset;
137 my $bytes_written = 0;
138 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
139 while ($bytes_to_write > 0) {
140 $bytes_written = syswrite ($sock, $msg,
141 $bytes_to_write, $offset);
142 if (!defined($bytes_written)) {
143 if (_err_will_block($!)) {
144 # Should happen only in deferred mode. Record how
145 # much we have already sent.
146 $conn->{send_offset} = $offset;
147 # Event handler should already be set, so we will
148 # be called back eventually, and will resume sending
151 delete $conn->{send_offset};
152 $conn->handle_send_err($!);
154 return 0; # fail. Message remains in queue ..
157 $offset += $bytes_written;
158 $bytes_to_write -= $bytes_written;
160 delete $conn->{send_offset};
163 last unless $flush; # Go back to select and wait
164 # for it to fire again.
166 # Call me back if queue has not been drained.
168 set_event_handler ($sock, "write" => sub {$conn->_send(0)});
170 set_event_handler ($sock, "write" => undef);
175 sub _err_will_block {
176 if ($blocking_supported) {
177 return ($_[0] == EAGAIN());
181 sub set_non_blocking { # $conn->set_blocking
182 if ($blocking_supported) {
183 # preserve other fcntl flags
184 my $flags = fcntl ($_[0], F_GETFL(), 0);
185 fcntl ($_[0], F_SETFL(), $flags | O_NONBLOCK());
189 if ($blocking_supported) {
190 my $flags = fcntl ($_[0], F_GETFL(), 0);
191 $flags &= ~O_NONBLOCK(); # Clear blocking, but preserve other flags
192 fcntl ($_[0], F_SETFL(), $flags);
196 sub handle_send_err {
197 # For more meaningful handling of send errors, subclass Msg and
199 my ($conn, $err_msg) = @_;
200 warn "Error while sending: $err_msg \n";
201 set_event_handler ($conn->{sock}, "write" => undef);
204 #-----------------------------------------------------------------
205 # Receive side routines
208 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
209 my ($pkg, $my_host, $my_port, $login_proc) = @_;
210 my $self = $pkg->new($login_proc);
212 $self->{sock} = IO::Socket::INET->new (
213 LocalAddr => $my_host,
214 LocalPort => $my_port,
218 die "Could not create socket: $! \n" unless $self->{sock};
219 set_event_handler ($self->{sock}, "read" => sub { $self->new_client } );
228 while ($msg = shift @{$conn->{inqueue}}){
229 &{$conn->{rproc}}($conn, $msg, $!);
234 sub _rcv { # Complement to _send
235 my $conn = shift; # $rcv_now complement of $flush
236 # Find out how much has already been received, if at all
237 my ($msg, $offset, $bytes_to_read, $bytes_read);
238 my $sock = $conn->{sock};
239 return unless defined($sock);
242 $conn->set_non_blocking();
243 $bytes_read = sysread ($sock, $msg, 1024, 0);
244 if (defined ($bytes_read)) {
245 if ($bytes_read > 0) {
247 @lines = split /\r?\n/, $msg;
249 $lines[0] = $conn->{msg} . $lines[0] if exists $conn->{msg};
251 $lines[0] = $conn->{msg} if exists $conn->{msg};
252 push @lines, '' unless @lines;
257 $conn->{msg} = pop @lines;
259 push @{$conn->{inqueue}}, @lines if @lines;
261 $conn->{msg} .= $msg;
265 if (_err_will_block($!)) {
273 if (defined $bytes_read && $bytes_read == 0) {
274 # $conn->disconnect();
275 &{$conn->{rproc}}($conn, undef, $!);
276 delete $conn->{inqueue};
283 my $server_conn = shift;
284 my $sock = $server_conn->{sock}->accept();
285 my $conn = $server_conn->new($server_conn->{rproc});
286 $conn->{sock} = $sock;
287 my $rproc = &{$server_conn->{rproc}} ($conn, $sock->peerhost(), $sock->peerport());
289 $conn->{rproc} = $rproc;
290 my $callback = sub {_rcv($conn)};
291 set_event_handler ($sock, "read" => $callback);
292 } else { # Login failed
300 set_event_handler ($conn->{sock}, "read" => undef);
301 $conn->{sock}->close;
304 #----------------------------------------------------
305 # Event loop routines used by both client and server
307 sub set_event_handler {
308 shift unless ref($_[0]); # shift if first arg is package name
309 my ($handle, %args) = @_;
311 if (exists $args{'write'}) {
312 $callback = $args{'write'};
314 $wt_callbacks{$handle} = $callback;
315 $wt_handles->add($handle);
317 delete $wt_callbacks{$handle};
318 $wt_handles->remove($handle);
321 if (exists $args{'read'}) {
322 $callback = $args{'read'};
324 $rd_callbacks{$handle} = $callback;
325 $rd_handles->add($handle);
327 delete $rd_callbacks{$handle};
328 $rd_handles->remove($handle);
335 my ($pkg, $time, $proc, $recur) = @_;
337 my $class = $obj || $pkg;
338 my $self = bless { t=>$time + time, proc=>$proc }, $class;
339 $self->{interval} = $time if $recur;
340 push @timerchain, $self;
347 @timerchain = grep {$_ != $self} @timerchain;
351 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
352 my ($conn, $r, $w, $rset, $wset);
355 # Quit the loop if no handles left to process
356 last unless ($rd_handles->count() || $wt_handles->count());
359 IO::Select->select ($rd_handles, $wt_handles, undef, $timeout);
362 foreach $r (@$rset) {
363 &{$rd_callbacks{$r}} ($r) if exists $rd_callbacks{$r};
365 foreach $w (@$wset) {
366 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
369 # handle things on the timer chain
371 if ($now >= $_->{t}) {
373 $_->{t} = $now + $_->{interval} if exists $_->{interval};
378 @timerchain = grep { $_->{t} > $now } @timerchain;
380 if (defined($loop_count)) {
381 last unless --$loop_count;