2011-06-20 23 views
1

以下代碼是(僞!)http服務器。它只是發回http請求。
來自瀏覽器的ftp請求會發生意想不到的情況,如ftp://localhost:8888/。有了這個,瀏覽器連接並保持永久連接。Perl套接字作爲(僞)http服務器與ftp請求斷開!

我不明白髮生了什麼!
如何控制此行爲並忽略ftp請求?

#!/usr/bin/perl 
use strict; 
use Socket; 
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); 
use IO::Poll; 

local *S; 
socket  (S, PF_INET , SOCK_STREAM , getprotobyname('tcp')) || die "socket: $!\n"; 
setsockopt (S, SOL_SOCKET, SO_REUSEADDR, 1) || die "setsockopt: $!\n"; 
bind  (S, sockaddr_in(8888, INADDR_ANY)) || die "bind: $!\n"; 
listen  (S, 10) || die "listen: $!\n"; 
fcntl(S, F_SETFL, fcntl(S, F_GETFL, 0) | O_NONBLOCK) || die "fcntl: $!\n"; 

my $poll=IO::Poll->new; 
$poll->mask(*S => POLLIN|POLLOUT); 


while(1) { 
    $poll->poll(); 
    for my $reader ($poll->handles(POLLIN)) { 
     my $remote = accept (my $connection, $reader); 
     my $bytes= sysread $connection,my $header,1024; 

     if (defined $bytes) { 
      if ($bytes == 0 || (index $header,"\r\n\r\n") < 0) { 
       close $remote; 
       next; 
      } 
     } else { 
      close $connection; 
      next; 
     } 

     syswrite $connection,"HTTP/1.1 200 OK\r\n\r\n".$header; 
     close $connection; 
    } 
} 

回答

4

與HTTP不同,FTP以服務器向客戶端發送問候語開始。在這種情況下,客戶端認爲它正在與FTP服務器通話,等待FTP hello,而服務器認爲它正在與HTTP客戶端通話,正在等待它發送HTTP命令。

解決方法是在嘗試執行sysread之前爲客戶端套接字($connection)設置超時。

相關問題