主頁 > 知識庫 > perl Socket編程實例代碼

perl Socket編程實例代碼

熱門標簽:武漢呼叫中心外呼系統(tǒng)線路商 開封百應電銷機器人聯(lián)系方式 買了外呼系統(tǒng)不想用了怎么辦 電話機器人電話卡封號怎么辦 浦東上海400開頭的電話申請 北京語音電銷機器人價格 真人語音電銷機器人系統(tǒng) 樂昌電話機器人 邯鄲外呼調(diào)研線路

在networking方面,最基礎的是BSD socket編程,但往往perl入門時在這個方面,最頭疼的無疑是如何開始,如何Step by step。最好的藥方就是Example,一段完整的可以運行(working)的代碼,通過實踐來感受遠比看枯燥的manual來得深刻。

     以下給出幾段使用Socket及IO::Socket編寫的Server/client,他們能實現(xiàn)最簡單但是卻最基本的任務,包括一個forking/accept的模型??梢灾苯訌椭七@些代碼,然后小加修改即可開發(fā)一些小型的tcp/udp應用了。

TCP 客戶端, Socket 模塊

簡介:實現(xiàn)從服務器端讀取一行信息然后返回

復制代碼 代碼如下:

#!/usr/bin/perl -w
# tcp_socket_cli.pl
use strict;
use Socket;
my $addr = $ARGV[0] || '127.0.0.1';
my $port = $ARGV[1] || '3000';
my $dest = sockaddr_in($port, inet_aton($addr));
my $buf = undef;
socket(SOCK,PF_INET,SOCK_STREAM,6) or die "Can't create socket: $!";
connect(SOCK,$dest)                or die "Can't connect: $!";
my $bs = sysread(SOCK, $buf, 2048); # try to read 2048
print "Received $bs bytes, content $buf\n"; # actually get $bs bytes
close SOCK;

執(zhí)行結(jié)果:
perl tcp_socket_cli.pl localhost 25
Received 41 bytes, content 220 ESMTP Postfix - ExtMail 0.12-hzqbbc

TCP 服務端 Socket模塊, forking/accept模型
簡介:一個多進程的TCP服務器,sample中實現(xiàn)了daytime的功能

復制代碼 代碼如下:

#!/usr/bin/perl -w
# tcp_socket_dt_srv.pl
use strict;
use Socket;
use IO::Handle;
use POSIX qw(WNOHANG);
my $port     = $ARGV[0] || '3000';
my $proto    = getprotobyname('tcp');
$SIG{'CHLD'} = sub {
     while((my $pid = waitpid(-1, WNOHANG)) >0) {
          print "Reaped child $pid\n";
      }
};
socket(SOCK, AF_INET, SOCK_STREAM, getprotobyname('tcp'))
    or die "socket() failed: $!";
setsockopt(SOCK,SOL_SOCKET,SO_REUSEADDR,1)
    or die "Can't set SO_REUSADDR: $!" ;
my $my_addr = sockaddr_in($port,INADDR_ANY);
bind(SOCK,$my_addr)    or die "bind() failed: $!";
listen(SOCK,SOMAXCONN) or die "listen() failed: $!";
warn "Starting server on port $port...\n";
while (1) {
     next unless my $remote_addr = accept(SESSION,SOCK);
     defined(my $pid=fork) or die "Can't fork: $!\n";

     if($pid==0) {
          my ($port,$hisaddr) = sockaddr_in($remote_addr);
          warn "Connection from [",inet_ntoa($hisaddr),",$port]\n";
          SESSION->autoflush(1);
          print SESSION (my $s = localtime);
          warn "Connection from [",inet_ntoa($hisaddr),",$port] finished\n";
          close SESSION;
          exit 0;
      }else {
          print "Forking child $pid\n";
      }
}
close SOCK;

利用上述tcp_socket_cli.pl訪問該server的執(zhí)行結(jié)果:
[hzqbbc@local misc]$ perl tcp_socket_dt_srv.pl
Starting server on port 3000...
Connection from [127.0.0.1,32888]
Connection from [127.0.0.1,32888] finished
Reaped child 13927
Forking child 13927

TCP 客戶端 ,IO::Sockiet模塊
簡介:同樣為客戶端,不過使用的是IO::Socket 面向?qū)ο竽K

復制代碼 代碼如下:

#!/usr/bin/perl -w
# tcp_iosocket_cli.pl
use strict;
use IO::Socket;
my $addr = $ARGV[0] || '127.0.0.1';
my $port = $ARGV[1] || '3000';
my $buf = undef;
my $sock = IO::Socket::INET->new(
        PeerAddr => $addr,
        PeerPort => $port,
        Proto    => 'tcp')
    or die "Can't connect: $!\n";
$buf = $sock>;
my $bs = length($buf);
print "Received $bs bytes, content $buf\n"; # actually get $bs bytes
close $sock;

TCP 服務端, IO::Socket模塊, forking/accept模型
簡介:同樣的一個daytime
服務器,使用IO::Socket重寫。

復制代碼 代碼如下:

#!/usr/bin/perl
# tcp_iosocket_dt_srv.pl
use strict;
use IO::Socket;
use POSIX qw(WNOHANG);
$SIG = sub {
     while((my $pid = waitpid(-1, WNOHANG)) >0) {
          print "Reaped child $pid\n";
      }
};
my $port     = $ARGV[0] || '3000';
my $sock = IO::Socket::INET->new( Listen    => 20,
                                  LocalPort => $port,
                                  Timeout   => 60*1,
                                  Reuse     => 1)
  or die "Can't create listening socket: $!\n";
warn "Starting server on port $port...\n";
while (1) {
     next unless my $session = $sock->accept;
     defined (my $pid = fork) or die "Can't fork: $!\n";

     if($pid == 0) {
          my $peer = gethostbyaddr($session->peeraddr,AF_INET) || $session->peerhost;
          my $port = $session->peerport;
          warn "Connection from [$peer,$port]\n";
          $session->autoflush(1);
          print $session (my $s = localtime), "\n";
          warn "Connection from [$peer,$port] finished\n";
          close $session;
          exit 0;
      }else {
          print "Forking child $pid\n";
      }
}
close $sock;

現(xiàn)在再介紹使用Socket及IO::Socket模塊來進行Unix domain Socket的client/server開發(fā)。Unix Domain Socket(簡稱unix socket)和TCP/UDP等INET類型socket相比起來有幾個優(yōu)點:
1)、安全性高,unix socket只在單機環(huán)境中使用,不支持機器之間通信
2)、效率高,執(zhí)行時的速度約是TCP的兩倍,多用于操作系統(tǒng)內(nèi)部通信(IPC)
3)、支持SOCK_DGRAM,但和UDP不同,前后消息是嚴格有序的

因此使用Unix socket來設計單機的IPC應用是首選。非常實用。大量的Unix應用軟件都使用unix socket來進行程序間通信。

Unix Domain Socket客戶端, Socket模塊
簡介:使用Unix domain socket的客戶端。

復制代碼 代碼如下:

#!/usr/bin/perl -w
use strict;
use Socket;
use IO::Handle;
my $path = $ARGV[0] || '/tmp/daytime.sock';
socket(my $sock, PF_UNIX, SOCK_STREAM, 0);
my $sun = sockaddr_un($path);
connect($sock, $sun) or die "Connect: $!\n";
$sock->autoflush(1);
my $buf = $sock>;
my $bs = length($buf);
print "Received $bs bytes, content $buf\n";
close $sock;

Unix Domain Socket 服務端, Socket模塊
簡介:使用Unix domain socket實現(xiàn)的daytime服務器。
復制代碼 代碼如下:

#!/usr/bin/perl -w
# tcp_socket_dt_srv.pl
use strict;
use Socket;
use IO::Handle;
use POSIX qw(WNOHANG);
my $path     = $ARGV[0] || '/tmp/daytime.sock';
$SIG{'CHLD'} = sub {
      while((my $pid = waitpid(-1, WNOHANG)) >0) {
            print "Reaped child $pid\n";
        }
};
socket(SOCK, PF_UNIX, SOCK_STREAM, 0)
    or die "socket() failed: $!";
setsockopt(SOCK,SOL_SOCKET,SO_REUSEADDR,1)
    or die "Can't set SO_REUSADDR: $!" ;
unlink $path if -r $path;
bind(SOCK,sockaddr_un($path))    or die "bind() failed: $!";
listen(SOCK,SOMAXCONN)           or die "listen() failed: $!";
warn "Starting server on path $path...\n";
while (1) {
      next unless my $sockname = accept(SESSION,SOCK);
      defined (my $pid=fork) or die "Can't fork: $!\n";

      if($pid==0) {
          SESSION->autoflush(1);
          print SESSION (my $s = localtime);
          close SESSION;
          exit 0;
       }else {
          print "Forking child $pid\n";
       }
}
close SOCK;

您可能感興趣的文章:
  • 實現(xiàn)了基于TCP的Java Socket編程實例代碼
  • c# socket編程udp客戶端實現(xiàn)代碼分享
  • java socket編程實例代碼講解
  • php使用socket編程示例

標簽:松原 河北 宜春 六安 淄博 鄂州 石嘴山 自貢

巨人網(wǎng)絡通訊聲明:本文標題《perl Socket編程實例代碼》,本文關鍵詞  perl,Socket,編程,實例,代碼,;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《perl Socket編程實例代碼》相關的同類信息!
  • 本頁收集關于perl Socket編程實例代碼的相關信息資訊供網(wǎng)民參考!
  • 推薦文章