我正在尝试在 perl 中创建一个聊天服务器程序,其中客户端输入一些文本,服务器以输入的 ASCII 值的总和进行响应。但是,有一个问题。服务器正在正确处理数据,但客户端没有接收到它。这是代码:
#!usr/bin/perl
#client.pl
use strict;
use warnings;
use IO::Socket;
$| = 1;
print "Client Program\n";
my $lp = 12000;
my $client_socket = new IO::Socket::INET (
PeerAddr => '127.0.0.1',
PeerPort => $lp,
Proto => 'tcp'
) or die "Cannot create the socket: $!\n";
print "Server connected at port $lp \n";
print "Enter the text to sent to the server: \n";
my $user_input = <>;
chomp $user_input;
print $client_socket;
$client_socket->send($user_input);
my $server_output;
$client_socket->recv($server_output, 1024);
print "ASCII Sum received: scalar(<$client_socket>)";
$client_socket->close();
客户端在发送数据后就挂断了(我可以说是因为我看到了服务器程序中收到的文本。但是,在我终止客户端之前,服务器处理不会出现)。我不明白这里出了什么问题。我也可以发布服务器程序,但它似乎没有任何问题。
这是服务器程序:
#!/usr/bin/perl
#server.pl
use strict;
use warnings;
use IO::Socket;
$| = 1;
print "Server Program\n";
my $lp = 12000;
my $server_socket = new IO::Socket::INET (
LocalHost => '127.0.0.1',
LocalPort => $lp,
Proto => 'tcp',
Listen => SOMAXCONN,
Reuse => 1) or die "Cannot create the socket: $!\n";
my $sum_ASCII = 0;
print "Server started at port $lp \n";
print "Press Ctrl+C to stop the server\n";
print "Waiting for client to connect.. \n";
# or die sprintf "ERROR:(%d)(%s)(%d)(+%s)", $!,$!,$^E,$^E
while (my $new_client = $server_socket->accept()) {
my $addr = $new_client->peerhost();
my $port = $new_client->peerport();
print "Connected to client at $addr at port $port ";
while(<$new_client>) {
print "Following is the text entered by client: \n";
print "$_ \n";
my $len = length($_);
print "The length of the string is: $len\n";
my @char_array = split(//);
#print "@char_array";
print "Initially sum is $sum_ASCII\n";
for (my $i = 0; $i< $len; $i++)
{
print "Adding ASCII of '$char_array[$i]'.. ";
$sum_ASCII = $sum_ASCII + ord($char_array[$i]);
print "\t Sum = $sum_ASCII\n";
}
print "\n\nTotal sum of ASCII values of the all the sent characters is: $sum_ASCII\n"
}
print "Sending the sum to the client.. \n";
my $np = 98765;
my $client_socket = new IO::Socket::INET (
PeerAddr => '127.0.0.1',
PeerPort => $np,
Proto => 'tcp'
) or die "Cannot create the socket: $!\n";
print "Client connected at port $np \n";
$client_socket->send($sum_ASCII);
$client_socket->close();
print "\nClient now disconnecting..\n";
close $new_client;
print "\nWaiting for new client to connect.. \n";
}
#my $np = 12345
#my $client_socket = new IO::Socket::INET (
#LocalAddr => '127.0.0.1',
#PeerPort => $np,
#Proto => 'tcp'
#) or die "Cannot create the socket: $!\n";
#print "Client connected at port $np \n";
#$client_socket->send($sum_ASCII);
#$client_socket->close();
#print "Enter the text to sent to the server: \n";
#my $user_input = <>;
#chomp $user_input;
#print $client_socket;
#$new_client->send($sum_ASCII);
$server_socket->close();