开发者

How can I listen on multiple sockets in Perl?

开发者 https://www.devze.com 2022-12-13 18:28 出处:网络
I want to listen on different sockets on a TCP/IP client开发者_JAVA技巧 written in Perl. I know I

I want to listen on different sockets on a TCP/IP client开发者_JAVA技巧 written in Perl. I know I have to use select() but I don't know exactly how to implement it.

Can someone show me examples?


Use the IO::Select module. perldoc IO::Select includes an example.

Here's a client example. Not guarneteed to be typo free or even work right:

use IO::Select;
use IO::Socket;
# also look at IO::Handle, which IO::Select inherits from

$lsn1 = IO::Socket::INET->new(PeerAddr=>'example.org', PeerPort=>8000, Proto=>'tcp');
$lsn2 = IO::Socket::INET->new(PeerAddr=>'example.org', PeerPort=>8001, Proto=>'tcp');
$lsn3 = IO::Socket::INET->new(PeerAddr=>'example.org', PeerPort=>8002, Proto=>'tcp');
$sel = IO::Select->new;
$sel->add($lsn1);
$sel->add($lsn2);
# don't add the third socket to the select if you are never going to read form it.

while(@ready = $sel->can_read) {
    foreach $fh (@ready) {
        #read your data
        my $line = $fh->getline();
        # do something with $line
        #print the results on a third socket
        $lsn3->print("blahblahblah");
    }
}

this was too big to put in a comment field

You need to better define what you want to do. You have stated that you need to read from port A and write to port B. This is what the above code does. It waits for data to come in on the sockets $lsn1 and $lsn2 (ports 8000 and 8001), reads a line, then writes something back out to example.com on port 8002 (socket $lsn3).

Note that select is really only necessary if you need to read from multiple sockets. If you strictly need to read from only one socket, then scrap the IO::Select object and the while loop and just do $line = < $lsn1 > . That will block until a line is received.

Anyway, by your definition, the above code is a client. The code does actively connect to the server (example.org in this case). I suggest you read up on how IO::Socket::INET works. The parameters control whether it's a listening socket or not.

0

精彩评论

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