2013-04-08 100 views
0

任何人都可以指引我在IO :: Socket :: INET中開發的雙向客戶端服務器腳本,發送和接收短信? 我需要研究它的流程和工作。 TY。雙向客戶端服務器

+0

我一直想寫一個,但我有機器人能夠發展一個。我也無法找到合適的代碼。所以,如果你能告訴我一個.. – user2250900 2013-04-08 11:37:20

+1

你沒有通過這一個... http://stackoverflow.com/questions/15844918/2-way-communication-between-server-client-scripts – 2013-04-08 11:37:41

+0

這可以幫助,但不是雙向的,我猜測.. http://www.conceptsolutionsbc.com/perl-articles-mainmenu-41/25-modules-and-packages/54-writing-client-server-applications-using-iosocket – 2013-04-08 11:38:05

回答

1

這裏是上述問題的最簡單的解決方案:

服務器腳本

#!/usr/bin/perl 

use strict; 
use warnings; 
use IO::Socket::INET; 

my $socket; 
my $clientsocket; 
my $serverdata; 
my $clientdata; 

$socket = new IO::Socket::INET (
    LocalHost => '127.0.0.1', 
    LocalPort => '0155', 
    Proto => 'tcp', 
    Listen => 1, 
    Reuse => 1 
) or die "Oops: $! \n"; 
print "Waiting for the Client.\n"; 


$clientsocket = $socket->accept(); 

print "Connected from : ", $clientsocket->peerhost();  # Display messages 
print ", Port : ", $clientsocket->peerport(), "\n"; 

# Write some data to the client 
$serverdata = "This is the Server speaking :)\n"; 
print $clientsocket "$serverdata \n"; 

# read the data from the client 
$clientdata = <$clientsocket>; 
print "Message received from Client : $clientdata\n"; 

$socket->close(); 

客戶端腳本:

#!/usr/bin/perl 

use strict; 
use warnings; 
use IO::Socket::INET; 

my $socket; 
my $serverdata; 
my $clientdata; 

$socket = new IO::Socket::INET (
    PeerHost => '127.0.0.1', 
    PeerPort => '0155', 
    Proto => 'tcp', 
) or die "$!\n"; 

print "Connected to the Server.\n"; 

# read the message sent by server. 
$serverdata = <$socket>; 
print "Message from Server : $serverdata \n"; 

# Send some message to server. 
$clientdata = "This is the Client speaking :)"; 
print $socket "$clientdata \n"; 

$socket->close(); 
+0

這是一個甜蜜的代碼! :) TY – user2250900 2013-04-08 20:00:17

2

它就像任何其他文件句柄。

while (<$socket>) { # Receiving 
    print $socket $_; # Sending 
} 
+0

我可以從客戶端發送文本到服務器,但我無法將其發送到服務器(確認)。 是否需要等待響應或任何這樣的事情在編? – user2250900 2013-04-08 12:09:45

+3

當然你必須等待迴應。如果你的客戶沒有得到迴應而退出,它不會得到它。你需要等待,就像我展示服務器一樣。 – ikegami 2013-04-08 12:19:30