2015-10-05 75 views
0

我寫的東西中繼工作到其他機器(類似的Gearman)我這樣做,以瞭解socket編程,但我得到真的很困惑如何保持一個套接字連接開放將消息發送來回

期望中的工作流程: [客戶] - > [服務器] - > [worker1],[worker2]等

我打算送作業(URL)的數千所以我想創建一個新的socket每一個請求過度使用,我想保持服務器和客戶端以及服務器和工作者之間的活躍連接。

這是我實現,但我知道有一種更好的方式來做到這一點,我到處都找過網找的例子,但最後還是決定張貼在這裏的問題

use IO::Socket::INET; 
use feature qw(say); 
use strict; 

my $socket = new IO::Socket::INET (
    LocalHost => '0.0.0.0', LocalPort => '7779', 
    Proto => 'tcp', blocking => 1, Reuse => 1, Listen => 5 
) or die $!; 

while(1) 
{ 
    if(my $client_socket = $socket->accept() ){ 
     say "Client connected: " .$client_socket->peerhost . ":" . $client_socket->peerport; 

     my $last_msg_time = time;   
     while(1){ #I WILL MOVE THIS LOOP TO A CHILD PROCESS OR A THREAD 
      my $data; $client_socket->recv($data,1024); 
      if($data eq "*DISCONNECT" || time - $last_msg_time > 10){ 
       say "Timeout"; 
       last; 
      } 
      if($data){ 
       my $last_msg_time = time; 
       say "Received: $data"; 
       $client_socket->send("OK!"); 
      } 
     } 
    } 
} 

$socket->close; 

客戶端:

use IO::Socket::INET; 
use feature qw(say); 

my $socket = new IO::Socket::INET (
    PeerHost => '127.0.0.1',PeerPort => '7779', 
    Proto => 'tcp', blocking => 1 
) or die "Cannot connect to the server $!\n"; 

$socket->send("hello world"); 

my $response; $socket->recv($response, 1024); 
say "received response: $response"; 
$socket->send("hi again"); 

$socket->send("*DISCONNECT"); 


#shutdown($socket, 1); 
$socket->close(); 

回答

0

服務器需要保持插座的哈希映射,像這樣:

if (my $client_socket = $socket->accept()) { 
    $client_sockets{$client_socket->peerhost . ":" . $client_socket->peerport} = $client_socket; 
} 

和遍歷所有條目,以檢查是否有新的數據或斷開請求:

foreach my $key (keys %client_sockets) { 
    my ($host, $port) = split/:/,$key; 
    my $socket = $client_sockets{$key}; 
    #handle socket 
    delete $client_sockets{$key} if $disconnected; 
} 

你可能想踢一個工作線程爲每個新的socket。將線程句柄同樣存儲在哈希映射中。

相關問題