0

我想实现一些看似荒谬的事情。

我创建了一个创建服务器套接字的 PHP 脚本。我能够从 java 客户端连接到服务器套接字。

现在我想要的是在服务器端的某个地方维护这个套接字,以便我以后可以在需要时访问它。

但是,这里的问题是,一旦 respond() 函数终止,socket 就关闭了,Run 类中的 br.readLine() 方法接收到空行。

出于我的目的,readLine() 方法应该继续等待响应。

到目前为止我所做的...

regsock.php(应该在哪里注册套接字)

  <?php
    set_time_limit(0);
    $fh = fopen("reg.txt", "w");
    fwrite($fh, "SERVER Starting\r\n");
    $sersock = socket_create_listen(1234);
    fwrite($fh, "SERVER Running\r\n");

    while(true){
        respond();
    }

    function respond(){
        global $sersock, $fh;
        $sock = socket_accept($sersock);
        fwrite($fh, "Client Connected\r\n");
        echo "Client: ".socket_read($sock, 1024);
        socket_write($sock, "OK\n\r");

        //Some way to store client sockets?
    }
    socket_close($sersock);
    fclose($fh);
?>

运行.java

Socket socket = new Socket("localhost", 1234);

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                    socket.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));

bw.write("Server OK?");
bw.flush();
System.out.println("Server:"+br.readLine()); //Output-> Server:OK
System.out.println("Server:"+br.readLine()); //Output-> Server:
bw.close();
br.close();
socket.close();

而且,remote.php(我想访问 resgsock.php 上接受的套接字)

<?php
    $sock = //Retrieve socket resource here
    fwrite($sock, "REMOTE PAGE\r\n");
    echo "Socket write complete";
?>

是否有可能,或者我只是做错了一切。

这可以通过其他一些方法来完成。

4

1 回答 1

0

只有在与 regsock 相同的进程或子进程中执行 remote.php 时,regsock.php 中接受的套接字才能传递给 remote.php。

例如,您可以这样做:

# In global setup: handle child process termination automatically
# Might break calls to "system" though
pcntl_signal(SIGCHLD, SIG_IGN);

function respond(){
    global $sersock, $fh;
    $sock = socket_accept($sersock);
    fwrite($fh, "Client Connected\r\n");
    echo "Client: ".socket_read($sock, 1024);
    socket_write($sock, "OK\n\r");

    $pid = pcntl_fork();
    if ($pid == 0) {
        # This is now a subprocess. If I "include" remote.php
        # it can operate on $sock as if it was its own.
        include "remote.php";
        # Now exit the subprocess
        exit;
    } elsif ($pid < 0) {
        # fork failed, handle error
    } else {
        echo "Subprocess running with pid $pid!";
        # Close the copy of the socket in parent process,
        # subprocess has a copy of its own.
        socket_close($sock);
    }

}
于 2013-07-25T08:55:12.427 回答