下午,
我正在用 Perl 编写一个小型 UDP 客户端/服务器,但在发送文件时遇到一些问题。我知道我需要将文件分成 block (数据报)并将它们发送到服务器。
我一直在思考如何将文件分解成数据报并发送它们。到目前为止,我可以很好地建立 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();
最佳答案
您的代码已经将文件分解为 block 。通过调用<FILE>
每个 block 将是一行。但存在几个问题:
- 如果线路太长并且无法装入数据包,则无法传输
- UDP 不保证传送,因此接收方可能会丢失数据,甚至可能会重复数据
- UDP 不保证传输顺序,因此您的接收方可能会先收到较晚的数据
这些缺点对于文件传输来说可能是 Not Acceptable ,因此您需要在 UDP 之上添加层来解决它们,例如序列号以检测重复项并重新排序和确认以触发丢失数据的重新提交。或者您可以简单地使用 TCP,它已经内置了所有这些以及更多内容。
关于perl - 在 Perl 中通过 UDP 发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22286727/