php sockets read json array from java server

£可爱£侵袭症+ 提交于 2020-01-07 06:34:06

问题


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 is a an array encoded as json_encode($array).

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

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.


回答1:


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

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.



来源:https://stackoverflow.com/questions/6015826/php-sockets-read-json-array-from-java-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!