PHP Socket Java消息交换 [英] PHP Socket Java message exchange

查看:125
本文介绍了PHP Socket Java消息交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PHP页面和运行Java服务器之间进行通信。
只需通过套接字进行简单的字符串交换。

I'm trying to make a communication between a PHP page and running Java server. Just a simple string exchange through sockets.

这是我处理连接的线程的Java代码:

This is my Java Code for thread that handles the connection:

            InputStream in = clientSocket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

                String request;

                if((request=br.readLine())!=null){
                System.out.println("got the following request: " + request);
                out.write(request +"\n");
                out.flush();

                out.close();
                in.close();
                }

我用简单的Java客户端测试它,发送字符串然后接收结果将它打印回来并且有效。客户端和服务器都具有相同的输出。

I tested it with simple Java client that sends the string then receives the result and prints it back and it worked. Both client and the server had the same output.

这是我的PHP代码:

$fp = @fsockopen ($host, $port, $errno, $errstr);

if($fp){
    fputs($fp, $str);
    //echo fgets($fp);
}

close($fp);

将字符串发送到服务器,服务器接收它。
但是一旦我用fgets($ fp)取消注释,我被阻止,直到1-2分钟后发生某种超时。在该阻止期间,我的服务器没有收到任何内容
超时后我的服务器打印出来,它已收到该行,并可能发回响应,但是,PHP代码不会打印任何内容。

Which sends the string to the Server, and the Server receives it. But once I uncomment the line with fgets($fp) I am blocked until some sort of timeout happens after 1-2 minutes. During that Block my server is not receiving anything. After timeout my server prints, that it has received the line, and probably sends the response back, however, the PHP code doesn't print anything.

可能是什么问题?

提前谢谢。

PS可能值得一提的是,我通过AJAX访问此网页,因此它将结果回显回到另一页。

P.S. It is probably worth saying that I am accessing this web page through AJAX, so it "echoes" the result back to the other page.

推荐答案

我个人更喜欢 socket _ * 函数。但不管怎样,你可能都没有检查终止字符:

I prefer the socket_* functions, personally. But either way, you're likely missing checking for a terminating character:

$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_connect($sock, $host, $port);

socket_write($sock, $str);

$response = '';
while($resp = socket_read($sock, 1024)) {
    if(!$resp)
        break;
    $response .= $resp;
    if(strpos($resp, "\n") !== false)
        break;
}

echo "Server said: {$response}";

这篇关于PHP Socket Java消息交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆