2011-06-28 59 views
2

是否可以創建到終端設備上的打開端口的套接字連接。Perl套接字連接

如果連接丟失打印什麼東西?

我已經看到了一些例子,但他們需要服務器類型的腳本和客戶端,只是在尋找一個客戶端。

感謝

+0

,將Telnet服務器停止工作?我剛剛用80端口測試了這個sokething,並且腳本在我殺死它後運行... – mrlayance

回答

6

Perl有內置到它的插座。你只需要加載標準的Socket.pm模塊來獲得你需要的常量。

perlipc手冊頁告訴你所有關於這一點。然而,有許多更高級的模塊比內置模塊更容易獲得。有些甚至是標準的。

這裏有一個CLI例如:

% perl -MIO::Socket::INET -E '$him = new IO::Socket::INET "localhost:daytime" // die; print while <$him>' 
Tue Jun 28 08:17:13 2011 
+0

從'IO :: Socket :: INET-> new'有效返回'0'嗎?看起來好像不會。 – Axeman

+0

@Axeman,不。構造函數應該總是返回true。 '||'就夠了。 – tchrist

0

這方面的一個變化可能適合你的需要:如果我說連接到端口23例如

use strict; 
use warnings; 
use constant 
    { SOCKET_ERROR_MESSAGE => 'Some socket error message right here!' 
    , YOU_WANT_TO   => 1 
    }; 

use IO::Select; 
use IO::Socket::INET; 

@ARGV = qw<server.domain.tld 8080> unless @ARGV; 

sub handle_server_message { 
    ... 
} 

my $sel 
    = IO::Select->new(
     IO::Socket::INET->new( 
     PeerAddr => shift 
    , PeerPort => shift 
    )); 

# block until the server sends something that can be read. 
while (my ($sock) = $sel->can_read) { 
    # you could just do this with $sock->eof... 
    if ($sock->error and $sock->eof) { 
     die MY_ERROR_MESSAGE if YOU_WANT_TO; 
     print MY_ERROR_MESSAGE; 
    } 
    else { 
     handle_server_message($sock); 
    } 
}