Sending and receiving multiple JSON literals via PHP sockets -
i trying send json data 1 php script through sockets. following client code
$socket = socket_create(af_inet, sock_stream, sol_tcp); @socket_connect($socket, "localhost", 2429) or die("connect not opened"); $arr = ["hello", "i", "am", "a", "client"]; $count = 10; while($count-- > 0) { $msg = json_encode(["msg" => $arr[rand(0, 4)]]); // tried appending \n & \0 // $msg .= "\0"; // "\n"; echo "sending $msg \n"; socket_write($socket, $msg, strlen($msg)); }
the following code piece of server handles reception:
$count = 0; while(socket_recv($feed, $buf, 1024, 0) >= 1) { echo "obj ".++$count." : $buf"; // $obj = json_decode($buf); // error }
the problem is, on socket server side, json_decode unable parse data because of following situation:
expected output:
obj 1: {"msg":"i"} obj 2: {"msg":"a"} obj 3: {"msg":"a"} obj 4: {"msg":"i"} obj 5: {"msg":"a"} obj 6: {"msg":"client"} obj 7: {"msg":"am"} obj 8: {"msg":"am"} obj 9: {"msg":"am"}
the output get:
obj 1: {"msg":"i"}{"msg":"a"}{"msg":"a"}{"msg":"i"} obj 2: {"msg":"a"}{"msg":"client"}{"msg":"am"}{"msg":"am"} obj 3: {"msg":"am"}
i understand need tell server end of object
before sending next one, not know how. tried append "\n" , "\0" tell server end of stream, doesn't work. please me friends. thank in advance!
let's try adding length header, that's safest way go when strings involved.
your client needs send information, slight change original code in order: $msg = strlen($msg) . $msg;
(right after $msg = json_encode(["msg" => $arr[rand(0, 4)]]);
.
then, assuming $socket
opened, try server code (don't forget close sockets):
$lengthheader = ''; $jsonliteral = ''; while ($byte = socket_read($socket, 1)) { // reading 1 number @ time echo "read $byte\n"; if (is_numeric($byte)) { // $lengthheader .= $byte; } else if ($lengthheader) { echo "json seems start here. so...\n"; $nextmsglength = $lengthheader - 1; // except current 1 we've read (usually "[" or "{") echo "will grab next $nextmsglength bytes\n"; if (($partialjson = socket_read($socket, $nextmsglength)) === false) { die("bad host, bad!"); } $jsonliteral = $byte . $partialjson; $lengthheader = ''; // reset length header echo "grabbed json: $jsonliteral\n"; } else { echo "nothing grab\n"; } }
Comments
Post a Comment