我正在尝试通过 Unix 套接字实现一个简单的回显客户端/服务器。(我的最终目标是交换 JSON 数据,但这个例子是为了简单起见)。我不知道为什么客户端进程在第二次尝试打印到套接字时会消失在黑洞中。
服务器.pl:
use IO::Socket::UNIX;
my $socket_path = '/tmp/mysocket';
unlink $socket_path if -e $socket_path;
my $socket = IO::Socket::UNIX->new(
Local => $socket_path,
Type => SOCK_STREAM,
Listen => SOMAXCONN,
);
die "Can't create socket: $!" unless $socket;
while (1) {
next unless my $connection = $socket->accept;
chomp( my $line = <$connection> );
print $connection "$line\n";
}
客户端.pl:
use IO::Socket::UNIX;
my $socket = IO::Socket::UNIX->new(
Type => SOCK_STREAM,
Peer => '/tmp/mysocket',
);
die "Can't create socket: $!" unless $socket;
my $line;
print $socket "one\n";
chomp( $line = <$socket> );
say $line;
print $socket "two\n";
chomp( $line = <$socket> );
say $line;
say "three";
预期输出:
> ./client.pl
> one
> two
> three
实际输出:
> ./client.pl
> one