下午,
我在Perl中编写一个小型UDP客户端/服务器,并且在发送文件时遇到了一些问题。我知道我需要将文件分成块(数据报)并将它们发送到服务器。
我很难搞清楚如何将文件分解为数据报并发送它们。截至目前,我可以很好地建立UDP连接,服务器在收到UDP数据包时报告。这是我到目前为止,任何帮助将不胜感激!
服务器:
#!/usr/bin/perl
# Flushing to STDOUT after each write
$| = 1;
use warnings;
use strict;
use IO::Socket;
# Server side information
my $listen_port = 7070;
my $protocal = 'udp';
my $received_data = undef;
# Creating UDP socket for server
my $server = IO::Socket::INET->new (
LocalPort => $listen_port,
Proto => $protocal,
Type => SOCK_DGRAM
) or die "Socket could not be created, failed with error $!\n";
print "Waiting for client connection on port $listen_port\n";
open(FILE, ">output.UDP")
or die "File can not be opened: $!";
while($server->recv($received_data, 1024)) {
my $peer_address = $server->peerhost();
my $peer_port = $server->peerport();
print "Message was received from: $peer_address, $peer_port\n";
print FILE "$received_data";
}
close FILE;
print "Closing socket...\n";
$server->close();
客户端:
#!/usr/bin/perl
# Flushing to STDOUT after each write
$| = 1;
use warnings;
use strict;
use IO::Socket;
# Client side information
my $host = 'apollo.cselabs.umn.edu';
my $port = 7070;
my $protocal = 'udp';
my $datagram = undef;
# Creating UDP socket for client
my $client = IO::Socket::INET->new (
PeerAddr => $host,
PeerPort => $port,
Proto => $protocal,
Type => SOCK_DGRAM
) or die "Socket could not be created, failed with error: $!\n";
# Open and specified file
open(FILE, "10MBfile.dat")
or die "Fine can not be opened: $!";
$client->send("test");
# Send file line by line
while (<FILE>) {
$datagram = $_;
$client->send("$datagram");
}
close FILE;
# sleep(10);
$client->close();
答案 0 :(得分:4)
您的代码已经将文件拆分为块。通过调用<FILE>
,每个块将是一行。但是有几个问题:
文件传输可能无法接受这些缺点,因此您需要在UDP之上添加图层以解决这些问题,例如:用于检测重复的序列号,重新排序和确认以触发对丢失数据的重新提交。或者你可以简单地使用TCP而不是已经内置了所有这些内容。