- 论坛徽章:
- 0
|
- # cat svr.pl
- use strict;
- use IO::Socket;
- my $listen_socket = IO::Socket::INET->new(
- LocalPort => 1234,
- Listen => SOMAXCONN,
- Proto => 'tcp',
- Reuse => 1,
- Timeout => 30,
- );
- die "can't create socket: $@\n" unless defined $listen_socket;
- while ( 1 ) { # running on frontend
- next unless my $sock = $listen_socket->accept;
- my $peer_host = $sock->peerhost();
- my $mesg = '';
- while (<$sock>) {
- $mesg .= $_;
- }
- print $sock "welcome $peer_host, just echo back:\n";
- print $sock $mesg;
- $sock->close or die "can't close established socket $!\n";
- select(undef, undef, undef, 0.25);
- }
- # cat cli.pl
- use strict;
- use IO::Socket;
- my $sock=IO::Socket::INET->new(PeerAddr => '127.0.0.1',
- PeerPort => 1234,
- Proto => 'tcp')
- or die $@;
-
- print $sock "hello first line\n";
- print $sock "hello second line\n";
- $sock->shutdown(1); # tell peer I have finished writing
- print while <$sock>; # read from socket and print
- $sock->close or die $!;
复制代码
# perl svr.pl &
[1] 16704
# perl cli.pl
welcome 127.0.0.1, just echo back:
hello first line
hello second line
很久没写socket了~~
但用perl写socket是超级简单呀,顺手就搞定~
当然,复杂的svr/cli要考虑很多东西...
见偶的用Perl写一套监控系统,或Lincoln的书,或POE相关source.
【更新了一下:客户端当然可以一次发送多个命令。
另一般为了非阻塞,socket write和read可以分2个进程来做。】
[ 本帖最后由 兰花仙子 于 2009-11-26 21:14 编辑 ] |
|