使用套接字将PHP脚本连接到Java

时间:2019-03-13 21:09:44

标签: java php sockets

我正尝试用一个小的php脚本托管一个网络服务器,该脚本将一个行发送到Java程序(在本地计算机上),并从该程序返回一个行。之后,另一个客户端应该可以连接。我目前正在通过php脚本超时,无法弄清原因...

Java

public void start() {
        try {
            ServerSocket serversocket = new ServerSocket(port);
            while (true) {
                Socket client = serversocket.accept();

                PrintWriter out = new PrintWriter(client.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));


                String[] request = in.readLine().split(";");
                String answer = "";

                ...getting the answer...

                out.println(answer + "\n");
                out.close();
                in.close();
                client.close();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

PHP

<?php
$fp = fsockopen(getHostByName(getHostName()), 77777, $errno, $errstr, 5);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "test\n");
    echo fgets($fp, 128); 
    fclose($fp);
}
?>

1 个答案:

答案 0 :(得分:0)

好吧,我认为我在“得到答案”部分有一个永久循环。现在工作正常。 无论如何,这是我的新PHP代码:

<?php
    $sock = socket_create(AF_INET,SOCK_STREAM,0) or die("Cannot create a socket");
    socket_connect($sock,getHostByName(getHostName()),7777);
    $data = "arg1;arg2;arg3\n";
    socket_write($sock, $data, strlen($data));
    echo socket_read($sock, 2048);
    socket_close($sock);
?>

并确保在您的php.ini文件中添加/取消注释:

extension = sockets