2

Afternoon,

I am writing a small UDP Client/Server in Perl and am having some issues sending files. I understand I need to break the file into chunks (datagrams) and send them to the server.

I am stuck figuring out how to break the file up into datagrams and send them. As of now, I can establish a UDP connection just fine, the server reports when it is received a UDP packet. This is what I have so far, any help would be greatly appreciated!

Server:

#!/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();

Client:

#!/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();
4

1 回答 1

4

您的代码已经将文件分解成块。通过调用<FILE>每个块将是一行。但是有几个问题:

  • 如果线路太长并且无法放入数据包中,则无法传输
  • UDP 不保证传送,因此您的接收方可能会丢失数据甚至可能重复数据
  • UDP不保证发送顺序,所以你的接收者可能会先得到后面的数据

这些缺点对于文件传输可能是不可接受的,因此您需要在 UDP 之上添加层来解决它们,例如序列号以检测重复和重新排序以及触发丢失数据重新提交的确认。或者您可以简单地使用 TCP 代替,它已经内置了所有这些以及更多功能。

于 2014-03-09T19:23:55.960 回答