#!/bin/perl # Perl server-socket example # this version does not use the IO::Socket library, so it's more like C than Java use Socket; require "byteordering.pl"; # you'll need to download this too. my $PORT = $ARGV[0]; # port determined by command-line arg my ($saddr, $caddr); my $buffer = "abcdefghijklmnopqrstuvwxyz"; # binary (string) data buffer; my $d = 3.14; # double value my ($x, $y, $i, $j); # utility $byteorder = endiancheck(); # note: the data buffer cannot be empty! socket(sfd,AF_INET,SOCK_STREAM,getprotobyname('tcp')) || die "error"; $saddr = sockaddr_in($PORT,INADDR_ANY); bind(sfd,$saddr) || die "failed to bind"; listen(sfd,32); while (1) # server loop { accept (cfd,sfd); # accept connection, create communication socket cfd print "connection established\n"; # write an integer in binary mode $x = 10; # at this point, 10 is actually "10" !!! $y = pack("i",$x); # convert to binary representation (pack into an integer). $y = htonl($y); # host to network byte ordering syswrite(cfd,$y,4,0); # write 4 bytes starting from \$$y + 0 syswrite(cfd,$buffer,$x,0); # write $x bytes $i = sysread(cfd,$d,8,0); # read 8 bytes - treated as a string of 8 chars if ($i != 8) {die $!;} $d = unpack("d",$d); # convert to numerical representation; # the conversion between data formats is a bit harder than in C/Java because # Perl does not use much type information. # if we were just communicating strings, or with another perl host, then # socket IO would be much simpler: we can use <> to read and print to write. # - see the filecopy program and the perl http client for example. The only # slight complication in that case is the need for "autoflush". close(cfd); }