#!/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; }