Here's an 'OO-style' example (including a server part, so it can be run standalone):
#!/usr/bin/perl -w use strict; use IO::Socket; my $pid = fork(); unless ($pid) { # --- server my $server = IO::Socket::INET->new( #LocalAddr => 'localhost', LocalPort => 12345, Proto => "tcp", Listen => SOMAXCONN, Reuse => 1, ) or die "couldn't create listening socket: $!"; print "server listening...\n"; while (1) { my $client = $server->accept(); print "client connected\n"; while (<$client>) { if (/^foo/) { $client->print("bar"); # 3 bytes (dummy) $client->print("0000001f"); # 8 bytes length as hex s +tring $client->print("X" x 0x1f); # data last; } } $client->close(); print "connection closed\n"; } exit; } else { # --- client sleep 1; my $conn = MyConnection->new('localhost', 12345); $conn->WriteInfo("foo\n"); my $data = $conn->ReadData(); print "data: '$data'\n"; } END { kill 15, $pid; print "server shut down\n"; } package MyConnection; use base "IO::Socket::INET"; sub new { my $class = shift; my ($addr, $port) = @_; my $socket = IO::Socket::INET->new( Proto => "tcp", PeerAddr => $addr, PeerPort => $port, ) or die "couldn't connect: $!"; $socket->autoflush(); return bless $socket, $class; } sub WriteInfo { my $sock = shift; my $info = shift; print "client sending request\n"; $sock->print($info); } sub ReadData { my $sock = shift; $sock->read(my $dummy, 3); $sock->read(my $len_hex, 8); my $len = hex($len_hex); print "client reading response ($len bytes)\n"; $sock->read(my $data, $len); return $data; }
$ ./892650.pl server listening... client connected client sending request client reading response (31 bytes) data: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' connection closed server shut down
In reply to Re: Object Oriented Perl interface to read from and write to a socket
by Eliya
in thread Object Oriented Perl interface to read from and write to a socket
by Perllace
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |