我正在使用Perl通过套接字编程实现客户端 - 服务器通信。
我正在从客户端向服务器发送一些数据,但除非使用Ctrl-C终止客户端,否则我无法在服务器上看到任何内容。
此外,从服务器返回的任何内容都不会到达客户端。
这是我第一次尝试进行客户端 - 服务器编程,我不知道该怎么做。
我正在使用IO::Socket::INET
模块。
这是我的代码
服务器
use IO::Socket::INET;
my ($socket, $client_socket);
my ($peeraddress, $peerport);
$| = 1;
$socket = new IO::Socket::INET (
LocalHost => '127.0.0.1',
LocalPort => '5000',
Proto => 'tcp',
Listen => 5,
Reuse => 1
) or die "Error in socket creation: $!\n";
while (1) {
$client_socket = $socket->accept();
$data = <$client_socket>;
print "Received from socket is $data\n";
print "Sending to socket\n";
$client_socket->send("hello");
}
$socket->close();
客户端
use IO::Socket::INET;
$| = 1;
my($socket,$client_socket);
$socket = new IO::Socket::INET (
PeerHost => '127.0.0.1',
PeerPort => '5000',
Proto => 'tcp',
) or die "Error in socket creation : $!\n";
print $socket "mailshow 018DB3FCE4";
$socket->recv($data,1024);
print $data;
sleep(5);
$socket->close();
答案 0 :(得分:6)
冒险猜测是这样的:
$data = <$client_socket>;
$client_socket->send("hello");
print $socket "mailshow 018DB3FCE4";
$socket->recv($data,1024);
当您从$client_socket
读取文件句柄时,它正在尝试读取数据的行。此行数据由$/
定义,默认情况下为换行符(或文件结尾)。您不发送换行符,以便$data= <$client_socket>
阻止,直到您终止该过程。
我想如果你:
undef $/
\n
send
/ recv
你不会有这个问题。
有关示例,请参阅perlipc
。请,请 - 打开strict
和warnings
。在寻求帮助时,这是唯一的礼貌。
这似乎可以做你想要的:
use strict;
use warnings;
use IO::Socket::INET;
$| = 1;
my $socket = new IO::Socket::INET(
PeerHost => '127.0.0.1',
PeerPort => '5000',
Proto => 'tcp',
) or die "Error in socket creation : $!\n";
print {$socket} "mailshow 018DB3FCE4\n";
my $data;
$socket->recv( $data, 1024 );
print "Client received: ",$data,"\n";
sleep(5);
$socket->close();
use strict;
use warnings;
use IO::Socket::INET;
$| = 1;
my $socket = new IO::Socket::INET(
LocalHost => '127.0.0.1',
LocalPort => '5000',
Proto => 'tcp',
Listen => 5,
Reuse => 1
) or die "Error in socket creation: $!\n";
while (1) {
my $client_socket = $socket->accept();
my $data = <$client_socket>;
print "Received from socket is $data\n";
print "Sending to socket\n";
$client_socket->send("hello");
}
$socket->close();
虽然作为一种风格点 - 我强烈建议反对在您的代码中混合print
/ <>
和send
/ recv
- 这是导致混乱的好方法。
e.g:
print {$socket} "mailshow 018DB3FCE4\n";
my $data = <$socket>;
print "Client received: ",$data,"\n";
和
my $data = <$client_socket>;
print "Received from socket is $data\n";
print "Sending to socket\n";
print {$client_socket} "hello\n";