Perl套接字文件传输问题

时间:2014-03-03 22:27:55

标签: perl sockets tcp file-transfer

我的连接工作和数据传输工作....在某种程度上。我正在设计一个设置客户端和服务器套接字的小程序。连接后,客户端可以将文件发送到服务器。

我的问题是,当我开始发送我的“测试”文件时,服务器永远不会结束它的while循环。它不断将数据连接到输出文件中。更奇怪的是,输出文件中的数据是正确的,除了行之间有额外的空白区域。

我知道这是因为我没有选择\ n字符,我在服务器上添加了另一个\ n字符。但如果我选择了客户端,那么一切都在一条线上。因此,服务器(无论是否添加换行符)都会在一行中输出所有内容,因为它只接收一行。如果我在服务器端选择,我会得到一个空的文本文件......这让我很困惑。

此外,服务器永远不会停止连接......即使客户端断开连接,它也会产生无限循环。终端无限期地输出:

Use of uninitialized value $data in concatenation (.) or string at ./tcp_server.pl line 51, <GEN2> line 14.

以下是我的服务器代码:

#!/usr/bin/perl

# Flushing to STDOUT after each write
$| = 1;

use warnings;
use strict;
use IO::Socket::INET;
use v5.10;

# Server side information
my $listen_port  = '7070';
my $protocal     = 'tcp';

# Finds IP address of host machine
# Connects to example site on HTTP
my $ip_finder = IO::Socket::INET->new(
   PeerAddr=> "www.google.com",
   PeerPort=> 80,
   Proto   => "tcp"
) or die "The IP can not be resolved: $!\n";

# The found IP address of Host
my $ip_address = $ip_finder->sockhost;

# Creating socket for server
my $server = IO::Socket::INET->new (
    LocalPort   => $listen_port,
    Proto       => $protocal,
    Listen      => 5,
    Reuse       => 1,
) or die "Socket could not be created, failed with error: $!\n"; # Prints error code
print    "Socket created using IP: $ip_address\n";
print    "Waiting for client connection on port $listen_port\n";

# Accept connection
my $client_socket = $server->accept();

open(my $fh, ">out")
    or die "File can not be opened: $!";
while($client_socket) {

    # Retrieve client information
    my $client_address = $client_socket->peerhost();
    my $client_port    = $client_socket->peerport();
    print "Client accepted: $client_address, $client_port\n";

    my $data = <$client_socket>;
    print $fh "$data\n";

}
close $fh;
$server->close();

和客户:

#!/usr/bin/perl

# Flushing to STDOUT after each write
$| = 1;

use warnings;
use strict;
use IO::Socket::INET;
use v5.10;

# Client side information
# Works by setting $dest to server address, needs to be on same domain
# my $dest      = '<IP goes here>';
# my $dest      = '<IP goes here>';
my $dest        = '<host>.cselabs.umn.edu';
my $port        = '7070';
my $protocal    = 'tcp';

my $client = IO::Socket::INET->new (
    PeerHost    =>  $dest,
    PeerPort    =>  $port,
    Proto       =>  $protocol,
) or die "Socket could not be created, failed with error: $!\n"; # Prints error code

print "TCP connection established!\n";

open(my $fh, "<test")
    or die "Can't open: $!";
while(my $line = <$fh>) {
    print $client $line;
}
close $fh;
# sleep(10);
$client->close();

1 个答案:

答案 0 :(得分:1)

您不在客户端添加换行符。客户端只是从文件中读取一行(包括换行符)并将其打印到套接字,但不添加另一个换行符。但是在服务器上,您从套接字(包括换行符)读取行并添加另一个换行符。此外,服务器中的循环条件不正确。您不应检查套接字是否存在,因为即使在连接关闭后它仍然存在。相反,您应该在阅读时检查错误(这是您未定义警告的来源)。并且,最好不要逐行读取,而是独立于行的块,例如

while (read($client_socket, my $data, 8192)) {
    print $fh $data;
}