我正在尝试使用Perl中的套接字创建聊天服务器.但是,当我运行Server程序时,我收到错误:
"错误:(9)(错误的文件描述符)(6)(+句柄无效)在Server.pl第21行."
当我运行客户端程序时,我收到错误:
"无法创建套接字:无法建立连接,因为目标计算机主动拒绝它."
这是Server程序:
#!usr/bin/perl
#server.pl
use IO::Socket;
$| = 1;
print "Server Program\n";
my $lp = 12000;
my $server_socket, $new_client, $addr, $port;
$server_socket = new IO::Socket::INET (
LocalHost => '127.0.0.1',
LocalPort => $lp,
Proto => 'tcp',
Reuse => 1) or die "Cannot create the socket: $!\n";
print "Server started at port $lp \n";
while (1) {
$new_client = $server_socket->accept() or die sprintf "ERROR:(%d)(%s)(%d)(+%s)", $!,$!,$^E,$^E;
$addr = $new_client->peerhost();
$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 "$_";
}
print "Client now disconnecting..\n";
close $new_client;
}
$server_socker->close();
Run Code Online (Sandbox Code Playgroud)
这是客户:
#!usr/bin/perl
#client.pl
use IO::Socket;
$| = 1;
print "Client Program\n";
my $lp = 12000;
my $client_socket = new IO::Socket::INET (
PeerHost => '127.0.0.1',
PeerPort => $lp,
Proto => 'tcp',
Reuse => 1) or die "Cannot create the socket: $!\n";
print "Server connected at port $lp \n";
print "Enter the text to sent to the server: \n";
$user_input = <>;
chomp $user_input;
print $plient_socket;
$client_socket->send($user_input);
$client_socket->close();
Run Code Online (Sandbox Code Playgroud)
我是新手,我没有得到我出错的地方.有人可以帮忙吗?
您试图从没有收听的套接字接受连接.加
Listen => SOMAXCONN,
Run Code Online (Sandbox Code Playgroud)
现在有关您的代码的非主题评论:
一直用use strict; use warnings;.它将突出显示代码的其他一些问题.
对shebang线上的相对路径没有任何意义.你错过了一个/.
在样式方面,在变量使用之前声明变量被认为是不好的形式.声明变量的重点是限制它们的范围,因此在程序顶部声明它们会违背目的.
LocalHost => '127.0.0.1'(写得更好LocalHost => INADDR_LOOPBACK)使它只能从127.0.0.1接收连接.这可能很有用,但我不知道你是否故意这样做过.默认值INADDR_ANY允许来自任何接口的连接.