我有我的连接工作和数据传输工作......在某种程度上。我正在设计一个设置客户端和服务器套接字的小程序。一旦连接,客户端就可以发送文件到服务器。Perl套接字文件传输问题
我的问题是,当我开始发送我的“测试”文件时,服务器永远不会结束它的while循环。它将数据连接到输出文件中。更奇怪的是,输出文件中的数据是正确的,除了行之间有额外的空白。
我知道这是因为我没有咀嚼\ n字符,而是在服务器上添加了另一个\ n字符。但是,如果我在客户身上唠叨,那么一切都在一条线上。因此,服务器(不管它是否添加换行符)都将其输出到一行,因为它只收到一行。如果我在服务器端chomp,我得到一个空的文本文件......这让我感到困惑。
此外,服务器从不停止连接......即使在客户端断开连接后,它也会造成无限循环。终端输出这种无限期:
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();
这是不是一个好主意,揭示您正在使用的机器的IP地址,特别是当开发一个完全不关心安全的协议! – salva
我明白了,这有些不同。这个范围非常小。这是一个家庭作业,我只是有点麻烦。通过显示IP,我可以将它输入到我的客户端。这对我在不同的主机上运行时很好。它只是让我更容易。我完全理解这个问题! – rusty
我的意思是,任何人读这个线程将能够访问您的服务器和滥用其错误来控制机器。 – salva