#!/usr/bin/perl -w
# server2way.pl - a server that reads from
# and writes to a client
use strict;
use IO::Socket;
use Sys::Hostname;
my $port=shift||9000;
my $sock = new IO::Socket::INET(
LocalHost => 'localhost',
LocalPort => $port,
Proto => 'tcp',
Listen => SOMAXCONN,
Reuse => 2)
or die "no socket :$!";
STDOUT->autoflush(1);
my($new_sock, $buf);
while ($new_sock = $sock->accept()) {
# got a client connection, so read
# line by line until end-of-file
while (defined($buf = <$new_sock>)) {
# respond to client request using
# a cleverly disguised switch
# statement
foreach ($buf) {
/^PORT$/ and
print($new_sock "$port\n"),
print "$port\n",
last;
/^HELLO$/ and
print($new_sock "Hi\n"),
last;
/^NAME$/ and
print($new_sock hostname(),
"\n"),
last;
/^DATE$/ and
print($new_sock
scalar(localtime),
"\n"),
last;
# default case:
print $new_sock "DEFAULT\n";
}
}
close $new_sock;
}
####
#!/usr/bin/perl -w
# client2way.pl - a client that writes to
# and reads from a server
use strict;
use IO::Socket;
require "server2way.pl";
my $host = shift || 'localhost';
my $port = shift || 9000;
my $sock = new IO::Socket::INET(
PeerAddr => $host,
PeerPort => $port,
Proto => 'tcp');
$sock or die "no socket :$!";
# send message to server
print $sock "PORT\n";
#print port number
print scalar <$sock>;
print $sock "HELLO\n";
# print server response to STDOUT
print scalar <$sock>;
# send and print more stuff
print $sock "NAME\n";
print scalar <$sock>;
print $sock "DATE\n";
print scalar <$sock>;
print $sock "NONE\n";
print scalar <$sock>;
close $sock;
####
#!/usr/bin/perl -w
# client2way.pl - a client that writes to
# and reads from a server
use strict;
use IO::Socket;
#require "server2way.pl";
my $host = shift || '(I'm entering the address of the server machine here")';
my $port = shift || 9000;
my $sock = new IO::Socket::INET(
PeerAddr => $host,
PeerPort => $port,
Proto => 'tcp');
$sock or die "no socket :$!";
# send message to server
print $sock "PORT\n";
#print port number
print scalar <$sock>;
print $sock "HELLO\n";
# print server response to STDOUT
print scalar <$sock>;
# send and print more stuff
print $sock "NAME\n";
print scalar <$sock>;
print $sock "DATE\n";
print scalar <$sock>;
print $sock "NONE\n";
print scalar <$sock>;
close $sock;