Search code examples
javaphpsocketswebsocketphpwebsocket

Sockets: Why does my message from the server always get split up into the exact same 2 messages?


This php snippet is on the server-side:

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) 
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";


//bind the socket to the ip address and port
if (socket_bind($sock, $address, $port) === false) 
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";  

//make the socket listen for connections, SOMAXCONN is the max limit of queued sockets waiting to 
//connect
if (socket_listen($sock, SOMAXCONN) === false) 
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";

if (($client= socket_accept($sock)) === false) 
    echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";

if ( false === ($id = socket_read($client, 10, PHP_NORMAL_READ)) )
    socket_close( $client ); //close the socket connection

$talkback = "PHP: Your id is '$id'.\n";
socket_write($client, $talkback, strlen($talkback));

This java snippet is on the client-side:

while ((inputLine = in.readLine()) != null) 
    Log.i( "MY_TAG", "Message received: " + inputLine);

Where inputLine is a String, and in is the inputstream of my client-side socket.

The output is ALWAYS:

Message received: Your id is '1

Message received: '.


Solution

  • You are reading the $id from the socket and in PHP_NORMAL_READ reading is terminated by a newline, so $id == "1\n". Just trim() it:

    $id = trim($id);
    //or
    $talkback = "PHP: Your id is '" . trim($id) . "'.\n";