下午,
我在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();
您的代码已将文件拆分为多个块。通过调用<FILE>
每个块将是一行。但是有几个问题:
这些缺点在文件传输中可能是无法接受的,因此您需要在UDP之上添加层来解决它们,例如,序列号以检测重复,并重新排序和确认以触发对丢失数据的重新提交。或者,您可以简单地使用TCP,而TCP已经内置了所有这些功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句