在单个提示符下使用IO :: Socket :: INET接收和发送消息

时间:2016-11-25 13:03:38

标签: perl

我在网站上发现了两种基于IO :: Socket :: INET模块的程序,它通过IP地址接收和发送消息。

接收消息程序:

use IO::Socket::INET;
my $text;
$MySocket=new IO::Socket::INET->new (LocalPort=>1234,Proto=>'udp');
while(1)
{
    $MySocket->recv($text,128);
    $hostip=$MySocket->peerhost();
    if($text ne '')
    {
        print "\nReceived message from $hostip: $text \n";
        print "Command Output:\n";
        #system("$text");
        print "\n";
    }
    else
    {
        print "Client has exited!"; exit 1;
    }
}

发送消息:

use IO::Socket::INET;
#Enter Destination IP Message
print "Please Enter the destination IP: \n";
$DestinationIP = <STDIN>;
chomp $DestinationIP;

#Enter message to sent to Server
print "Please Enter your message: \n";
$MySocket=new IO::Socket::INET-> new(PeerPort=>1234,Proto=>1234,Proto=>'udp',PeerAddr=>$DestinationIP);
#$MySocket->send($msg);

while($msg=<STDIN>)
{
    chomp $msg;
    if($msg ne '')
    {
        print "\n Sending $msg";
        if($MySocket->send($msg))
        {
            print "done \n";
            print "\nPlease Enter another message:";
        }
    }
}

我的问题是如何在单个MS-Dos提示符中处理/合并这些程序。

例如:

   `Receiving and sending message in Single Prompt.`

如果我毫无意义地质疑任何假设,我真诚地道歉。

1 个答案:

答案 0 :(得分:1)

请参阅第23行和第26行旁边的注释

use strict;
use warnings;
use IO::Socket::INET;
my @Destination;
my $text;
my $Receive_Socket=new IO::Socket::INET->new (LocalPort=>1234,Proto=>'udp');
while(1)
{
$Receive_Socket->recv($text,128);
my $hostip=$Receive_Socket->peerhost();
if($text ne '')
{
    print "\nReceived message from $hostip: $text \n";
    print "Command Output:\n";
    #system("$text");
    print "\n";

}
else
{
    print "Client has exited!"; exit 1;
}
push @Destination, $hostip;    # Push the IP Received to where you will send it
}
my $DestinationIP = $Destination[0]; # Here we assign the original $hostip to $DestinationIP
chomp $DestinationIP;

print "Please Enter your message: \n";
my $Send_Socket=new IO::Socket::INET-> new(PeerPort=>1234,Proto=>1234,Proto=>'udp',PeerAddr=>$DestinationIP);
while(my $msg=<STDIN>)
{
chomp $msg;
if($msg ne '')
{
    print "\n Sending $msg";
    if($Send_Socket->send($msg))
    {
        print "done \n";
        print "\nPlease Enter another message:";
    }
}
}