PHP套接字从Java服务器读取JSON数组 [英] php sockets read json array from java server

查看:105
本文介绍了PHP套接字从Java服务器读取JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TCP/IP连接到用JAVA编写的服务器.我的应用程序将json数组发送到此服务器,并且在某些情况下还希望获得一些结果,即json数组.问题是我可以通过tcp轻松发送json,但是在读取脚本时,该脚本将永久冻结,直到超时. 这是我的代码.

I am connecting to a server written in JAVA using TCP/IP. My application sends json arrays to this server and in some cases also expects some results, json arrays. The problem is that i can easily send json via tcp but when reading it the script freezes waiting forever until it timeouts. Here is my code.

$sock = socket_create(AF_INET, SOCK_STREAM, 0)  //Creating a TCP socket
                or die("error: could not create socket\n");
        $succ = socket_connect($sock, Application_Model_Config::serverHost, Application_Model_Config::serverPort)   //Connecting to to server using that socket
                or die("error: could not connect to host\n");

        socket_write($sock, $send.'\n', strlen($send)+1);

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

        echo "Server said: {$response}";
    }

$ send是一个编码为json_encode($ array)的数组.

$send is a an array encoded as json_encode($array).

可以发送,但是在需要接收时我什么也没收到.

Sending is ok but when needed to receive i don't get anything.

如果可以的话,我不介意使用jquery处理此问题(从服务器发送并获取json对象).我不知道任何实现这样的实现的方法,但是我愿意接受建议……实际上更喜欢它而不是php.

I wouldn't mind handling this using jquery (sending and getting json objects from the server) if that would be possible. I am not aware of any implementation that achieves something like this but i'm opened to suggestions...actually would prefer it instead of php.

推荐答案

在该模式下,您使用的是 socket_read ,它的语义与 recv

In the mode you're using socket_read, it has the same semantics as recv:

如果套接字上没有可用的消息,则接收调用将等待消息到达,除非套接字是非阻塞的(请参见fcntl(2)),在这种情况下,将返回值-1且外部变量errno设置为EAGAIN.接收呼叫通常会返回任何可用数据,直到请求的数量为止,而不是等待收到请求的全部数量.

If no messages are available at the socket, the receive calls wait for a message to arrive, unless the socket is nonblocking (see fcntl(2) ), in which case the value -1 is returned and the external variable errno set to EAGAIN. The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested.

因此,如果脚本一直等待直到超时",那是因为没有要读取的数据.您可以使用数据包嗅探器对此进行确认.

Therefore, if the script is "waiting forever until it timeouts" that's because there's no data to read. You can confirm this with a packet sniffer.

这篇关于PHP套接字从Java服务器读取JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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