in reply to Windows TCP socket client hangs in perlipc code
BrowserUK's answer is a good one.
If you really want to do this on Windows, you're not far off. Just don't do the fork, but make sure that for every line written from the server, there's a corresponding read in the client code. Also, you need to terminate each to/from the socket with a newline "\n".
Here's how I modified your server code:
And in conjunction with the following, modified client code, they work together well:#!/usr/bin/perl -w use IO::Socket; use Net::hostent; # for OO version of gethostbyaddr $PORT = 9000; # pick something not in use $server = IO::Socket::INET->new( Proto => 'tcp', LocalPort => $PORT, Listen => SOMAXCONN, Reuse => 1); die "can't setup server" unless $server; print "[Server $0 accepting clients]\n"; while ($client = $server->accept()) { $client->autoflush(1); print $client "Welcome to $0; type help for command list.\n"; $hostinfo = gethostbyaddr($client->peeraddr); my $response = $hostinfo ? $hostinfo->name : $client->peerhost; printf "[Connect from %s]\n", $response; print $client "Command?\n"; while ( <$client>) { next unless /\S/; # blank line if (/quit|exit/i) { last; + } elsif (/date|time/i) { print $client "SELECTED: date/time\n" +; } elsif (/who/i ) { print $client "SELECTED: who\n"; + } elsif (/cookie/i ) { print $client "SELECTED: cookie\n"; + } elsif (/motd/i ) { print $client "SELECTED: motd\n"; + } else { print $client "Commands: quit date who cookie motd\n"; } } continue { print $client "Command?\n"; } close $client; }
#!/usr/bin/perl -w use strict; use IO::Socket; my ($host, $port, $kidpid, $handle, $line); unless (@ARGV == 2) { die "usage: $0 host port" } ($host, $port) = @ARGV; # create a tcp connection to the specified host and port $handle = IO::Socket::INET->new(Proto => "tcp", PeerAddr => $host, PeerPort => $port) or die "can't connect to port $port on $host: $!"; $handle->autoflush(1); # so output gets there right away print STDERR "[Connected to $host:$port]\n"; # Get/display handshake message from server my $handshake = <$handle>; print $handshake; # Socket loop while (1) { my $servermsg = <$handle>; print $servermsg; while (1) { $line = <STDIN>; last if defined($line); } print $handle $line; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Windows TCP socket client hangs in perlipc code
by Anonymous Monk on Oct 20, 2007 at 00:46 UTC | |
by liverpole (Monsignor) on Oct 20, 2007 at 13:39 UTC |