ddzeko has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks,
I'm writing a daemon that will listen on UNIX socket, accept connections, take a request, crunch a bit on it, and spit out a response.
A problem arises when server closes connection after writing out on socket what it had to say. Somehow the data gets lost and client never receives it.
A kludge is to add sleep(1) just before the close. But, this is not acceptable in "production" application because it severely limits throughput to less than 1 msg/sec.
Is there a way to make IO::Socket::UNIX do a REAL FLUSH on that UNIX socket so client could read the data that's been written to it?
Here is the server's code:
#!/usr/bin/perl -w use IO::Socket::UNIX; use strict; my $sockfile = '/tmp/mysocket'; my $r; unlink($sockfile); my $usock = new IO::Socket::UNIX( Type => SOCK_STREAM, Local => $sockfile, Listen => 1) || die "ERROR: $!\n"; while (1) { if (($r) = $usock->accept) { my $out = do_something($r); $r->printflush($out); # sleep 1; # this makes it work $r->close; } } sub do_something { my ($fh) = @_; my ($l) = <$fh>; return uc($l); }
And here is my sample UNIX socket client:
#!/usr/bin/perl -w use IO::Socket::UNIX; my ($sockfile) = shift || die "$0: Socket address required\n"; my $r; my $usock = new IO::Socket::UNIX (Type => SOCK_STREAM, Peer => $sockfile) || die "ERROR: $!\n"; # read stdin and write to socket while(<>) { print $usock $_; } # shut down writing side (server receives EOF) $usock->shutdown(1); $sock->blocking(1); # this does not help # read socket (blocking) and write to stdout while(<$usock>) { print $_; } # shut down reading side $usock->shutdown(0);
I've tried SO_LINGER stuff (snippet found on google/groups) in server...
my $linger = pack('ii', 1, 120); # BSD struct $usock->sockopt(SO_LINGER, $linger);
But to no avail.
PLEASE HELP!!™ :)
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: IO::Socket::UNIX close() discards data when called "too soon"?
by pfaut (Priest) on Jan 20, 2004 at 14:58 UTC | |
by Anonymous Monk on Jan 20, 2004 at 15:05 UTC | |
by pfaut (Priest) on Jan 20, 2004 at 15:15 UTC | |
by ddzeko (Acolyte) on Jan 20, 2004 at 16:00 UTC | |
by Anonymous Monk on Jan 20, 2004 at 16:21 UTC |