O'Reilly logo

Mastering Perl/Tk by Nancy Walsh, Stephen Lidie

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Polling Win32 Sockets

If fileevent fails us in a Win32 environment, a simple and effective remedy, suggested by Brand Hilton, is to poll the socket ourselves. Here we have a simple poll daemon that works on Unix and Win32. It waits for a connect on port 10254 and outputs 5 bytes on the socket every five seconds. (Please excuse the lack of error processing.)

use IO::Socket;
use Tk;
use strict;

my $socket = IO::Socket::INET->new(
    Listen    => 5, 
    Reuse     => 1, 
    LocalPort => 10254, 
    Proto     => 'tcp',
) or die "Couldn't open socket: $!";

my $new_sock = $socket->accept(  );
while (1) {
    syswrite $new_sock, "polld";
    sleep 5;
}

Given that, we’d expect the following Tk poll client to work in both operating environments. The client packs a Text widget, connects to the poll daemon, and creates a fileevent handler to read the incoming socket data and append it to the Text widget. It works perfectly under Unix, but alas, on Win32, the I/O handler is never called.

use IO::Socket;
use Tk;
use strict;

my $mw = MainWindow->new;
my $text = $mw->Text->pack;
my $sock = IO::Socket::INET->new(PeerAddr => 'localhost:10254');
die "Cannot connect" unless defined $sock;
$mw->fileevent($sock, 'readable' => \&read_sock);
MainLoop;

sub read_sock {
    my $numbytes = 5;	
    my $line;
    while ($numbytes) {
        my $buf;
        my $num = sysread $sock, $buf, $numbytes;
        $numbytes -= $num;
        $line .= $buf;
    }
    $text->insert('end',"$line\n");
}

Here’s a revised poll client that still uses fileevent for Unix. But if it’s running under Win32, it creates ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required