我确实有以下用 perl 编写的客户端和服务器。问题是客户端永远不会正确地从服务器发送和接收消息。要求是向服务器发送消息并从服务器获取响应并基于此做出决定。我已经用 STDOUT 和 STDIN 编写了一个服务器客户端测试类,并且工作正常。我认为这是因为我在每次发送命令后按 ENTER 键。
客户
#!/usr/bin/perl
my $rhostname='192.168.0.181';
my $hostname="support";
my $port='7071';
my $script_log_dir="/var/sdplog/support";
use IO::Socket;
use strict;
$| = 1;
my $host_ip='0.0.0.0';
my $host_port='7088';
my $sock = new IO::Socket::INET (
PeerAddr => $rhostname,
PeerPort => $port,
Proto => 'tcp',
);
die "Could not create socket: $!\n" unless $sock;
$sock->autoflush(1);
my $query = "START:192.168.0.20:3:1:1:".$host_ip.":".$host_port;
my $count=0;
print "sending $query\n";
print $sock "$query";
my $data = <$sock>;
print $data;
close($sock);
服务器 - 代码
while ($q != -999){
$logger->debug('waiting for socket....');
my $new_sock = $sock->accept();
# sleep(5);
$i++;
$logger->debug($i.' accept');
while(<$new_sock>) {
# print $_;
$logger->debug("received command - ".$_);
my $ip_status = 2;
@input_command = split(':', $_);
$command = @input_command[0];
$server_ip = @input_command[1];
$retry_count= @input_command[2];
$wait_time = @input_command[3];
$next_ping_wait = @input_command[4];
$client_ip = @input_command[5];
$client_port = @input_command[6];
@ping_array=($server_ip,$retry_count,$wait_time,$next_ping_wait);
$logger->debug("received request ".@input_command);
$logger->debug($command);
if ($command eq "START"){
$logger->debug($command." received. checking server status");
$ip_status = network->ping_ip(@ping_array);
$logger->debug("ping status - ".$ip_status);
# $logger->debug($client_ip.$client_port);
# send_message($client_ip,$client_port,$ip_status); # do some
sleep(2);
print $new_sock "$ip_status\n";
}else{
$logger->debug($command." received"); }
}
}
close($sock);
exit 0;
服务器处于监听状态。当我运行客户端时,下面是输出。
>perl client.pl
sending START:192.168.0.20:3:1:1:0.0.0.0:7088
在服务器上
2012/08/21 18:49:04 DEBUG> server.pl:89 main:: - waiting for socket....
2012/08/21 18:49:08 DEBUG> server.pl:93 main:: - 1 accept
但仅此而已。一旦我单击 CTRL+C 客户端终止并按预期打印服务器上的其余日志。似乎没有刷新从服务器读取。
2012/08/21 18:56:05 DEBUG> server.pl:97 main:: - received command - START:192.168.0.20:3:1:1:0.0.0.0:7088
2012/08/21 18:56:05 DEBUG> server.pl:113 main:: - received request 7
2012/08/21 18:56:05 DEBUG> server.pl:114 main:: - START
2012/08/21 18:56:05 DEBUG> server.pl:116 main:: - START received. checking server status
2012/08/21 18:56:05 DEBUG> network.pm:31 network::ping_ip - 192.168.0.20 is alive
2012/08/21 18:56:05 DEBUG> server.pl:118 main:: - ping status - 1
2012/08/21 18:56:07 DEBUG> server.pl:89 main:: - waiting for socket....
但是没能找到解决办法。请说明一下,因为我现在被困了几个小时。