2014-04-23 50 views
0

我试图用Perl编写战舰,可以通过网络播放。 问题是我只能够在同一个控制台上打印,而不能通过套接字在其他控制台上打印。Perl:通过套接字打印

客户:

$socket = new IO::Socket::INET(
    PeerHost => '127.0.0.1', 
    PeerPort => '5005', 
    Protocol => 'tcp' 
) or die "Socket konnte nicht erstellt werden!\n$!\n"; 

print "Client kommuniziert auf Port 5005\n"; 

while ($eing ne ".\n") { 
    $eing = <> ; 
    print $socket "$eing"; 
} 

服务器:

$socket = new IO::Socket::INET(
    LocalHost => '127.0.0.1', 
    LocalPort => '5005', 
    Protocol => 'tcp', 
    Listen => 5, 
    Reuse  => 1 
) or die "Socket konnte nicht erstellt werden!\n$!\n"; 

while (1) { 
    $client_socket = $socket -> accept(); 
    $peeraddress = $client_socket -> peerhost(); 
    $peerport  = $client_socket -> peerport(); 

    $eing = ""; 
    while ($eing ne ".\n") { 
     print "while"; 
     &ausgabe; 
    } 
} 

sub ausgabe { 
    foreach $crt_board (@board2) { 
     foreach $spalte (@$crt_board) { 
      print $client_socket "$spalte ";  
     } 
     print $client_socket "\n"; 
    } 
} 

结果应该是一个板看起来像这样。

1 2 3 4 5 
1 ? ? ? ? ? 
2 ? ? ? ? ? 
3 ? ? ? ? ? 
4 ? ? ? ? ? 
5 ? ? ? ? ? 
+0

你希望哪个输出? –

+0

我将它添加到问题中。 – ProfGhost

+0

因此,我想你有一个“板”输入文件,你喂给客户端,不是吗? –

回答

2

如果您希望将数据从服务器传输到客户端,则需要从套接字读取数据,反之亦然。请始终使用严格(和警告)。下面将让你开始:

客户:

use strict; 
use IO::Socket::INET; 

my $socket = new IO::Socket::INET(
    PeerHost => '127.0.0.1', 
    PeerPort => '5005', 
    Protocol => 'tcp' 
) or die "Socket konnte nicht erstellt werden!\n$!\n"; 

print "Client kommuniziert auf Port 5005\n"; 

while (1) { 
    my $data; 
    $socket->recv($data, 64); 
    print $data; 
    last if $data =~ m#\.\n#; 
} 

服务器:

use strict; 
use IO::Socket::INET; 

my $socket = new IO::Socket::INET(
    LocalHost => '127.0.0.1', 
    LocalPort => '5005', 
    Protocol => 'tcp', 
    Listen => 5, 
    Reuse  => 1 
) or die "Socket konnte nicht erstellt werden!\n$!\n"; 

while (my $client_socket = $socket -> accept()) { 
    my $peeraddress = $client_socket -> peerhost(); 
    my $peerport  = $client_socket -> peerport(); 

    ausgabe($client_socket); 
} 

sub ausgabe { 
    my $client_socket = shift; 
    my @board2 = ([" ", 1,2,3],[1,"?","?","?"], 
        [2,"?","?","?"], [3,"?","?","?"]); 
    foreach my $crt_board (@board2) { 
     foreach my $spalte (@$crt_board) { 
      $client_socket->send("$spalte ");  
     } 
     $client_socket->send("\n"); 
    } 
    $client_socket->send(".\n"); 
} 
+0

谢谢,这工作! – ProfGhost