0

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.