2013-01-10 39 views
2

我試圖用Perl中的套接字創建一個聊天服務器。然而,當我運行服務器程序中,我得到的錯誤:perl聊天服務器錯誤

"ERROR:(9)(Bad file descriptor)(6)(+The handle is invalid) at Server.pl line 21."

,當我運行客戶端程序出現錯誤:

"Cannot create the socket: No connection could be made because the target machine actively refused it."

這裏是服務器程序:

#!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(); 

這裏是客戶端:

#!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(); 

我對此很陌生,我不明白我要去哪裏錯了。任何人都可以幫忙嗎?

回答

6

您試圖從未偵聽的套接字接受連接。添加

Listen => SOMAXCONN, 

現在有關你的代碼題外話評論:

  • 始終使用use strict; use warnings;。它會突出顯示您的代碼的其他一些問題。

  • 它對shebang線上的相對路徑沒有任何意義。您錯過了/

  • 在樣式上,它被認爲是一種糟糕的形式,在變量使用之前聲明變量。聲明變量的重點在於限制它們的範圍,因此在程序的頂部聲明它們是違反目的的。

  • LocalHost => '127.0.0.1'(最好寫成LocalHost => INADDR_LOOPBACK)使它只能接收來自127.0.0.1的連接。這可能很有用,但我不知道你是否有意這樣做。默認的INADDR_ANY允許來自任何接口的連接。

+0

嘿,非常感謝!這有幫助。我認爲如果我的默認值Listen是5,所以我沒有把它放在代碼中,認爲它會以默認值結束。 – TheRookierLearner

+0

不好的事情,因爲'Listen => 5'會破壞你的客戶端。 – ikegami