Interrupted Server Socket Connections 
Author Message
 Interrupted Server Socket Connections

        Hello. I am trying to write a client-server system using sockets. In the
code that I have written, the client reads lines of text from standard input and
sends them to the server, which prints the lines to standard output. Under
normal situations, it work fine. However, when I interrupt the server process,
the client does not realize that the server has disconnected until it sends
two (not one, but two!) more lines of output. Why is this happening, and how
can I detect when the connection has closed sooner?

        The code follows. I am running under Solaris 5.6. Thank you for any help
you can provide me.

Here is the server code (

#!/usr/local/bin/perl -w
use strict;

use sigtrap;
use Socket;

$SIG{PIPE} = sub { die "Broken Pipe.\n"; };

$| = 1;

my $port = $ARGV[0] || 2345;
socket SERVER, PF_INET, SOCK_STREAM, getprotobyname 'tcp' or die "socket: $!";
setsockopt SERVER, SOL_SOCKET, SO_REUSEADDR, pack("l", 1)
        or die "setsockopt: $!";
bind SERVER, sockaddr_in($port, INADDR_ANY) or die "bind: $!";
listen SERVER, SOMAXCONN or die "listen: $!";

my $paddr;
while($paddr = accept CLIENT, SERVER) {
        my ($port, $iaddr) = sockaddr_in $paddr;
        my $name = gethostbyaddr $iaddr, AF_INET;

        while(<CLIENT>) {

        close CLIENT;



Here is the client code (

#!/usr/local/bin/perl -w
use strict;

use sigtrap;
use Socket;

my ($remote, $port, $iaddr, $paddr);

$SIG{PIPE} = sub { die "Broken Pipe.\n"; };

$remote = shift || 'localhost';
$port = shift || 2345;  # random port
$port =~ /\D/ and $port = getservbyname $port, 'tcp';
die "No port" unless $port;
$iaddr = inet_aton($remote) or die "No host: $remote";
$paddr = sockaddr_in($port, $iaddr);

socket SOCKET, PF_INET, SOCK_STREAM, getprotobyname 'tcp' or die "socket: $!";
connect SOCKET, $paddr or die "connect: $!";
select SOCKET;
$| = 1;
select STDOUT;

while(<STDIN>) {
        print SOCKET or die "print: $!";


close SOCKET or die "close: $!";


                                                - Lyle Goldman

Mon, 01 Mar 2004 20:00:42 GMT  
 [ 1 post ] 

 Relevant Pages 

1. Interrupted Server Socket Connections

2. PERL5 - reading from a socket is not interrupted by an ALARM signal

3. Perl sockets vs. no sockets for chat server

4. Perl IO::Socket Establishing a socket with a Server

5. setting up a socket server client and server.....?

6. Persistant Perl socket connection?

7. Socket connection timeouts ?

8. Unable to accept more than one connection on a listening socket

9. I want to create as many thread as socket connection to read/write data (Win NT)

10. Socket Connections in Perl

11. trapping connection timeout ... using sockets

12. newbie: using socket connection to download file


Powered by phpBB® Forum Software