perl实例之同一台机器实现服务器端与客户端操作

发布时间:2020-07-24编辑:脚本学堂
本文分享一例perl代码,实现在同一台机器上的服务器端与客户端操作。

perl实例,演示在同一台机器上,操作服务端与客户端的例子。
代码:   
 

复制代码 代码示例:

#!/bin/perl

print "Server Started.n";
$AF_UNIX=1;     # The domain is AF_UNIX
$SOCK_STREAM=1; # The type is SOCK_STREAM
$PROTOCOL=0;    # Protocol 0 is accepted as the "correct protocol" by most systems.

socket(SERVERSOCKET, $AF_UNIX, $SOCK_STREAM, $PROTOCOL) || die " Socket $!n";
print "socket OKn";
$name="./greetings";
unlink "./greetings" || warn "$name: $!n";

bind(SERVERSOCKET, $name) || die "Bind $!n";
print "bind OKn";

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

while(1){
    accept(NEWSOCKET, SERVERSOCKET ) || die "Accept $!n";
    $pid=fork || die "Fork: $!n";
    if ($pid == 0 ){
         print (NEWSOCKET "Greetings from your server!!n";
         close(NEWSOCKET);
         exit(0);
    }else{
        close (NEWSOCKET);
    }
}