You are here iC Home > Perl > Perl for Sysad's > Perl Socket Server

Perl

6.3 Perl Socket Server

06.09.2008
6.2 whois Interface [  up  ] - [ a - z ] - [ search PC ] - [ top ] 6.4 HTML-ify

See also: [ Failover Sample with a Perl Socket Server ] - [ DevArticles.com ]


by Rahul Chauhan

#!/usr/bin/perl -w
# server0.pl
#--------------------

use strict;
use Socket;

# use port 7890 as default
my $port = shift || 7890;
my $proto = getprotobyname('tcp');

# create a socket, make it reusable
socket(SERVER, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1) or die "setsock: $!";

# grab a port on this machine
my $paddr = sockaddr_in($port, INADDR_ANY);

# bind to a port, then listen
bind(SERVER, $paddr) or die "bind: $!";
listen(SERVER, SOMAXCONN) or die "listen: $!";
print "SERVER started on port $port\n";

# accepting a connection
my $client_addr;
while ($client_addr = accept(CLIENT, SERVER)) {
	# find out who connected
	my ($client_port, $client_ip) = sockaddr_in($client_addr);
	my $client_ipnum = inet_ntoa($client_ip);
	my $client_host = gethostbyaddr($client_ip, AF_INET);
	# print who has connected
	print "got a connection from: $client_host", "[$client_ipnum]\n";
	# send them a message, close connection
	print CLIENT "Smile from the server";
	close CLIENT;
}

Starting the Socket Server

./socketserver.pl 7890 >/tmp/socketserver.log 2>/tmp/socketserver.err &


Client

#!/usr/bin/perl -w
# client1.pl - a simple client
#----------------

use strict;
use Socket;

# initialize host and port
my $host = shift || 'localhost';
my $port = shift || 7890;

my $proto = getprotobyname('tcp');

# get the port address
my $iaddr = inet_aton($host);
my $paddr = sockaddr_in($port, $iaddr);

# create the socket, connect to the port
socket(SOCKET, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
connect(SOCKET, $paddr) or die "connect: $!";

my $line;
while ($line = <SOCKET>) {
	print "$line\n";
}
close SOCKET or die "close: $!";


Socket Client in Ğuse strict safeğ fashion

Additionally, it sends a message to the Socket server

#!/usr/bin/perl -w
use strict;
################################################
# Socket Client
# (c) retoh :)
################################################
use Socket;

my $host = 'localhost';
my $port = 7890;

my $proto = getprotobyname('tcp');
socket(my $FS, PF_INET, SOCK_STREAM, $proto);
my $sin = sockaddr_in($port, inet_aton($host));
connect($FS, $sin) || exit -1;

my $old_fh = select($FS); $| = 1; select($old_fh);

print $FS "Hello at ", scalar localtime(), "\n\n";

while(<$FS>) {
        print;
}

close $FS;



Advanced search tips
6.2 whois Interface [  up  ] - [ top ] 6.4 HTML-ify



[ home ] - [ search ] - [ feedback ]

copyright by reto - created with mytexi