是否可以在另一个PHP脚本上使用接受的套接字?

时间:2013-07-25 08:38:37

标签: java php sockets

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

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

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

但是,问题是,只要response()函数终止,套接字就会关闭,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);
?>

Run.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";
?>

它是否可能,或者我只是做错了什么。

可以通过其他方法完成。

1 个答案:

答案 0 :(得分: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);
    }

}