套接字:为什么我来自服务器的消息总是被拆分成完全相同的 2 条消息?

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

此 php 片段在服务器端:

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));

此 java 片段在客户端:

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

其中 inputLine 是一个字符串,in 是我的客户端套接字的输入流。

输出总是:

Message received: Your id is '1

Message received: '.

您正在从套接字读取 $id,而在 PHP_NORMAL_READ 中,读取由换行符终止,因此 $id == "1\n"。只是 trim() 它:

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