Category: socket
Author/Contact Info
Description: This code shows few usefull routines for creating sockets with Perl. It`s a client that requires a compatible server (i`ve made one that works with this client, if you try to use it to connect to a telnet server you will get errors, if you want the server just contact me) . Probably it needs changes to get better, but im just learning.
#!/usr/bin/perl -w
# hash
# Client:

use strict ;
use Socket ;
my $ok = 0 ;
# Define the door:
my $port =  7000 ;
# Define the host (IP number only):
my $host = 127.0.0.1 ;

sub welcome () {
print <<EOF
###################################################
#                 Connected                       #
#-------------------------------------------------#
#                 on server                       #
###################################################

 exit to logout...
EOF
}

while (1) {
my $sockaddr = sockaddr_in($port, $host) || die "sockaddr: $!";
my $proto = (getprotobyname('tcp')) || die "proto: $!";

socket(SO, AF_INET, SOCK_STREAM, $proto) || die "socket: $!";
connect(SO, $sockaddr) || die "connect: $!";
if ($? == 0) {
         $ok++ ;
        }
if ($ok == 1) {
&welcome () ;
        }
my $msg = <STDIN> ;
if ("$msg" eq "exit\n") {
        --$ok ;
        print "$ok commands are successfully executed on remote server
+\n" ;
        exit 0 ;
}
send(SO, "$msg", 1024,0);
while (<SO>) {
        print ;
        }
}
#EOF
Replies are listed 'Best First'.
•Re: Socket TCP
by merlyn (Sage) on Oct 09, 2003 at 22:20 UTC
    Code that does a "use Socket" is working at the wrong level.
    use IO::Socket; my $sock = IO::Socket::INET->new("127.0.0.1:7000") or die "Cannot conn +ect: $!"; print "connected. enter command: "; my $cmd = <STDIN>; print $sock $cmd; while (<$sock>) { print; }
    Far simpler. Far easier to read. Far fewer magic constants.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Socket TCP
by NetWallah (Canon) on Oct 10, 2003 at 19:54 UTC
    The stuff between "while(1)" and "&welcome()}" should NOT be in a loop. merlyn's code IS so much nicer.
      It`s in a loop just to keep "connected", it`s my first socket in Perl, im searching for a better way to keep connected.