用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - perl代码库

perl tcp服务器端

2012-10-14 作者: 神马举报

[perl]代码库

#-----------------------------
use IO::Socket;

$server = IO::Socket::INET->new ( LocalPort => $server_port,
                                  Type      => SOCK_STREAM,
                                  Reuse     => 1,
                                  Listen    => 10 )   # or SOMAXCONN
          or die "Couldn't be a tcp server on port $server_port : $@\n";

while ( $client = $server->accept() )
{
# $client is the new connection
}

close ( $server );
#-----------------------------
use Socket;

# make the socket
socket ( SERVER, PF_INET, SOCK_STREAM, getprotobyname ( 'tcp' ) );

# so we can restart our server quickly
setsockopt ( SERVER, SOL_SOCKET, SO_REUSEADDR, 1 );

# build up my socket address
$my_addr = sockaddr_in ( $server_port, INADDR_ANY );
bind ( SERVER, $my_addr )
or die "Couldn't bind to port $server_port : $!\n";

# establish a queue for incoming connections
listen ( SERVER, SOMAXCONN )
or die "Couldn't listen on port $server_port : $!\n";

# accept and process connections
while ( accept ( CLIENT, SERVER ) )
{
# do something with CLIENT
}

close ( SERVER );
#-----------------------------
use Socket;

while ( $client_address = accept ( CLIENT, SERVER ) )
{
	( $port, $packed_ip ) = sockaddr_in ( $client_address );
	$dotted_quad = inet_ntoa ( $packed_ip );
# do as thou wilt
}
#-----------------------------
while ( $client = $server->accept() )
{
# ...
}
#-----------------------------
while ( ( $client,$client_address ) = $server->accept() )
{
# ...
}
#-----------------------------
use Fcntl qw ( F_GETFL F_SETFL O_NONBLOCK );

$flags = fcntl ( SERVER, F_GETFL, 0 )
         or die "Can't get flags for the socket: $!\n";

$flags = fcntl ( SERVER, F_SETFL, $flags | O_NONBLOCK )
         or die "Can't set flags for the socket: $!\n";
#-----------------------------


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...