perl - What is wrong with this IO::Socket::UNIX example? -
i trying implement simple echo client/server, on unix socket. (my ultimate goal exchange json data, illustration simplicity). have no thought why client process disappears black hole when tries print socket sec time.
server.pl :
use io::socket::unix; $socket_path = '/tmp/mysocket'; unlink $socket_path if -e $socket_path; $socket = io::socket::unix->new( local => $socket_path, type => sock_stream, hear => somaxconn, ); die "can't create socket: $!" unless $socket; while (1) { next unless $connection = $socket->accept; chomp( $line = <$connection> ); print $connection "$line\n"; }
client.pl :
use io::socket::unix; $socket = io::socket::unix->new( type => sock_stream, peer => '/tmp/mysocket', ); die "can't create socket: $!" unless $socket; $line; print $socket "one\n"; chomp( $line = <$socket> ); $line; print $socket "two\n"; chomp( $line = <$socket> ); $line; "three";
expected output:
> ./client.pl > 1 > 2 > 3
actual output:
> ./client.pl > 1
you set $socket->accept
phone call within while
loop. after server establishes connection , receives input client, next thing wants found new connection.
move accept
phone call outside while
loop
my $connection = $socket->accept; $connection->autoflush(1); while (my $line = <$connection> ) { chomp($line); print $connection "$line\n"; }
or, if want take more 1 connection,
while (1) { next unless $connection = $socket->accept; $connection->autoflush(1); while (my $line = <$connection>) { chomp($line); print $connection "$line\n"; } }
your current solution "suffering buffering", both server , client should set autoflush(1)
on socket handlers.
now handle simultaneous connections, server phone call fork
after getting connection, , handling connection in kid process.
while (1) { $connection = $socket->accept; if (fork() == 0) { $connection->autoflush(1); while (my $line = <$connection>) { chomp($line); print $connection "$line\n"; } close $connection; exit; } }
perl io-socket
No comments:
Post a Comment