Perl Socket example

Server Coding:

#!/usr/bin/perl
# unix_socket_server.pl

use strict;
use warnings;

use Socket;

print "Server Started.\n";
my $AF_UNIX = 1;
my $SOCK_STREAM = 1;
my $PROTOCOL = 0;
socket(SERVERSOCKET,$AF_UNIX,$SOCK_STREAM,$PROTOCOL) || die"Socket $!\n";
print "Socket OK\n";

my $name = "./.mysock";
unlink "$name" || warn "$name: $!\n";

bind(SERVERSOCKET,sockaddr_un($name)) || die "Bind$!\n";
print "Bind OK\n";

listen(SERVERSOCKET,5) || die "Listen $!\n";
print "Listen OK\n";

while(1) {
    accept(NEWSOCKET,SERVERSOCKET)|| die "Accept $!\n";
    defined(my $pid = fork) ||die "Fork: $!\n";
    if ($pid == 0) {
#   print(NEWSOCKET "Greetings from yourserver !!\n");

      open(FILE,"input.txt") || die "can not openinput.txt:$!\n";
      my@content = <FILE>;
      print"@content\n";
      close(FILE);

      print(NEWSOCKET @content);

      close(NEWSOCKET);
      exit(0);
    }
    else {
      close(NEWSOCKET);
    }
}

Client Coding:

#!/usr/bin/perl

use strict;
use warnings;

use Socket;
print "Hi I'm the client\n";
my $AF_UNIX = 1;
my $SOCK_STREAM = 1;
my $PROTOCOL = 0;
socket(CLIENTSOCKET,$AF_UNIX,$SOCK_STREAM,$PROTOCOL);

my $name="./.mysock";
my $result;
do {
    $result =connect(CLIENTSOCKET,sockaddr_un("$name"));
    if ($result != 1) {
      sleep(1);
    }
} while ($result != 1);

my $buf;
while(read(CLIENTSOCKET,my $data,500)) {
    $buf .= $data;
}
p

你可能感兴趣的:(Perl Socket example)