用Perl写的一个C/S模式的:
client端向本机端口消息发送消息,
server端监听本机端口,接收并响应client发送的消息。
也可以说是两进程间的socket通信。
实现很简单,但能稳定而良好地工作,
稍作改造,加些功能后,能用在很多类似需要C/S工作模式的场合。
server端代码:
#! /usr/bin/perl
###############################################################################
# \File
# tcp_server.pl
# \Descript
# listen to local port
###############################################################################
use IO::Socket::INET;
# 5277为监听端口
my $sock_listen = IO::Socket::INET->new(
LocalHost => '127.0.0.1',
LocalPort => 5277,
Proto => 'tcp',
Listen => 3,
Reuse => 1,)
or die "no socket: $!";
while(1)
{
my $sock_recv = $sock_listen->accept();
while ($data = <$sock_recv>)
{
print $data,"\n";
}
close $sock_listen;
}
client端代码:www.it165.net
#! /usr/bin/perl
###############################################################################
# \File
# tcp_client.pl
# \Descript
# send message to server
###############################################################################
use IO::Socket::INET;
my $sock_connect = IO::Socket::INET->new('127.0.0.1:5277');
die "Socket could not be created. Because$!\n" unless $sock_connect;
my $msg = "Hello, server.";
$sock_connect->print($msg);
close $sock_connect;
测试通过;