开发者

Perl socket connection

开发者 https://www.devze.com 2023-03-16 09:26 出处:网络
Is it possible to create a socket connection to an open port on 开发者_如何学Pythonan end device.

Is it possible to create a socket connection to an open port on 开发者_如何学Pythonan end device.

If the connection drops print something?

I have seen a few examples but they require a server type script and a client, just looking for a client.

Thanks


Perl has sockets built right into it. You just need to load the standard Socket.pm module to get the constants you need.

The perlipc manpage tells you all about this. There are many higher-level modules that get at this more easily than the builtins, however. Some are even standard.

Here’s a CLI example:

% perl -MIO::Socket::INET -E '$him = new IO::Socket::INET "localhost:daytime" // die; print while <$him>'
Tue Jun 28 08:17:13 2011


Consider using the module IO::Socket::INET, http://www.thegeekstuff.com/2010/07/perl-tcp-udp-socket-programming/


A variation of this might fit your need:

use strict;
use warnings;
use constant 
    { SOCKET_ERROR_MESSAGE => 'Some socket error message right here!'
    , YOU_WANT_TO          => 1
    };

use IO::Select;
use IO::Socket::INET;

@ARGV = qw<server.domain.tld 8080> unless @ARGV;

sub handle_server_message {
    ...
}

my $sel 
    = IO::Select->new(
      IO::Socket::INET->new( 
      PeerAddr => shift
    , PeerPort => shift
    ));

# block until the server sends something that can be read.
while ( my ( $sock ) = $sel->can_read ) { 
    # you could just do this with $sock->eof...
    if ( $sock->error and $sock->eof ) {
        die MY_ERROR_MESSAGE if YOU_WANT_TO;
        print MY_ERROR_MESSAGE;
    }
    else { 
        handle_server_message( $sock );
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消