【问题标题】:how to parse request URL in simple server in Perl which listen to port如何在 Perl 中侦听端口的简单服务器中解析请求 URL
【发布时间】:2016-05-27 15:21:05
【问题描述】:

这里是请求网址http://localhost:9009/?comd&user=kkc&mail=kkc@kkc.com

服务器perl脚本需要做哪些修改。

服务器-Perl-脚本

use IO::Socket;
use Net::hostent;       # for OO version of gethostbyaddr
$PORT = 9009;           # pick something not in use
$server = IO::Socket::INET->new( Proto     => 'tcp',
                                 LocalPort => $PORT,
                                 Listen    => SOMAXCONN,
                                 Reuse     => 1);

die "can't setup server" unless $server;
print "[Server $0 accepting clients]\n";
     while ($client = $server->accept()) 
     {
       $client->autoflush(1);
       print $client "Welcome to $0; type help for command list.\n";
       $hostinfo = gethostbyaddr($client->peeraddr);
       printf "[Connect from %s]\n", $hostinfo ? $hostinfo->name : $client->peerhost;
       print $client "Command? ";
       while ( <$client>) {
         next unless /\S/;       # blank line
            if (/comd/i )        { print  $client `dir`;      }
       } continue {
          print $client "Command? ";
       }
       close $client;
       print "client closed";
     }

【问题讨论】:

  • 首先使用 HTTP 服务器而不是原始套接字。
  • These answers 可能展示了在 Perl 中构建 HTTP 服务器的更好方法。

标签: perl


【解决方案1】:

我假设您的脚本不是用于生产,而是用于家庭作业或测试。 Perl 中有多种非常高效的 Web 服务器解决方案,例如带有 CGI 或 mod_perl 的 ApacheHTTP::Server::SimplePSGI/Plack

您通常还会使用像 DancerMojoCatalyst 这样的框架,它可以为您完成大部分无聊的标准工作:

use Dancer;

get '/' => sub {
    return 'Hi there, you just visited host '.request->host.
        ' at port '.request->port.' asking for '.request->uri;
};

回到您的问题:您的脚本是一个交互式服务器,而 HTTP 具有严格的请求和响应结构:

  1. 客户端连接到服务器
  2. 客户端发送请求
  3. 服务器发送响应

您需要删除交互部分,等待客户端开始对话:

use IO::Socket;
use Net::hostent;       # for OO version of gethostbyaddr
$PORT = 9009;           # pick something not in use
$server = IO::Socket::INET->new( Proto     => 'tcp',
                                 LocalPort => $PORT,
                                 Listen    => SOMAXCONN,
                                 Reuse     => 1);

die "can't setup server" unless $server;
print "[Server $0 accepting clients]\n";
     while ($client = $server->accept()) 
     {
       $hostinfo = gethostbyaddr($client->peeraddr);

       # Read request up to a empty line
       my $request;
       while ( <$client>) {
         last unless /\S/;
         $request .= $_;
       }

       # Do something with the request

       # Send response
       print $client "Status: 200 OK\r\nContent-type: text/plain\r\n\r\n".$request;

       close $client;
       print "client closed";
     }

服务器从客户端读取完整的请求并返回一个最小化的 HTTP 标头加上原始请求。

【讨论】:

    猜你喜欢
    • 2018-04-23
    • 2019-01-03
    • 1970-01-01
    • 2014-03-21
    • 2013-01-16
    • 1970-01-01
    • 2010-10-14
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多