簡體   English   中英

PHP與Perl套接字通信

[英]PHP To Perl Socket Communication

到目前為止,我已經編寫了一個Perl服務器,該服務器在后台連續運行,當它接收入站連接時,將分叉一個進程,然后處理該連接。 我最終希望它能夠執行的操作是通過套接字接受入站php連接,當然要運行這些命令,然后中繼並返回信息。 到目前為止,我已經設法在Perl腳本客戶端上使它100%工作,但是在php客戶端上卻不能100%工作。

[實際的發送和接收部分不是在此處粘貼文本的孔壁。]

print "Binding to port ...\n";
$server = IO::Socket::INET->new(
            Listen => 1, 
            LocalAddr => $_server, 
            LocalPort => $_port, 
            Proto => 'tcp', 
            Reuse => 1, Type => SOCK_STREAM) || die "Cant bind :$@\n";
$proccess = fork();
if ($proccess) {
    kill(0);
}
else {
    while(1) {
        while ($client = $server->accept()) {
            $client->autoflush(1);
            $con_handle = fork();
            if ($con_handle) {
                print "Child Spawned [$con_handle]\n";
            }else{
                while (defined($line = <$client>)) {
                    $command = `$line`;
                    print $client $command;
                }
                exit(0);
            }
        }
    }

正如我說的那樣,這在本地和遠程都可以用perl編寫的客戶端正常工作,但不能在php上100%地工作,我的意思是100%是服務器將接收命令但無法將其發送回的事實,或者服務器能夠接收該命令,但是客戶端無法讀取回復。

這是我工作最多的客戶端[php]。

$handle = fsockopen("tcp://xx.xx.xx.xx",1234);
fwrite($handle,"ls");
echo fread($handle);
fclose($handle);

這是工作中的perl客戶

#!/usr/bin/perl -w
use strict;
use IO::Socket;
my ($host, $port, $kidpid, $handle, $line);

unless (@ARGV == 2) { die "usage: $0 host port" }
($host, $port) = @ARGV;

# create a tcp connection to the specified host and port
$handle = IO::Socket::INET->new(Proto     => "tcp",
                                PeerAddr  => $host,
                                PeerPort  => $port)
       or die "can't connect to port $port on $host: $!";

$handle->autoflush(1);              # so output gets there right away
print STDERR "[Connected to $host:$port]\n";

# split the program into two processes, identical twins
die "can't fork: $!" unless defined($kidpid = fork());

# the if{} block runs only in the parent process
if ($kidpid) {
    # copy the socket to standard output
    while (defined ($line = <$handle>)) {
        print STDOUT $line;
    }
    kill("TERM", $kidpid);                  # send SIGTERM to child
}
# the else{} block runs only in the child process
else {
    # copy standard input to the socket
    while (defined ($line = <STDIN>)) {
        print $handle $line;
    }
}

如果有幫助,我可以在需要時發布整個服務器。

您的服務器希望客戶端發送線路。 但是您的PHP客戶端僅發送兩個字符“ ls”。 這意味着您的服務器將永遠等待客戶端發送換行符。

編輯:

  1. 您的Perl(服務器)代碼使用的是面向行的協議。 您的PHP代碼不是。 您不應混用兩種交流方式。
  2. 您的Perl客戶端確實使用面向行的協議。
  3. 您的PHP代碼應使用fgets()而不是fread()
  4. 在您的服務器中,父進程使客戶端的套接字保持打開狀態。 這就是為什么當孩子退出時套接字沒有關閉的原因,這也許就是為什么您的客戶端在另一個客戶端連接到服務器之前不會看到EOF的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM