简体   繁体   中英

How to read php socket connection response?

Following is my socket connection request and response order.

$socket = socket_create(AF_INET, SOCK_STREAM, 0);
$connection = socket_connect($socket, $Host, $Port);
$Md5CheckSum = md5($msg); 
$WillWait = 'SOAP  '. $Md5CheckSum. '  WILL_WAIT'."\n";
socket_write($socket,$WillWait);                        
socket_write($socket,$msg);
socket_write($socket,  SoapSender::$TERM_CHAR);
sleep(1);
$buf = socket_read($socket, 2048);
//socket_write($socket,"&\r\n");
echo "$buf\n";

Please could somebody tell me how to read response that I receive after last socket_write request. I have been searching for this answer all day but have not been able to find any help through Google.

Thanks a lot for your time.

Two functions should be used:

stream_set_blocking($socket, true);

And

stream_get_contents($socket);

Setting a block on your stream requires the return of data before your application will continue execution of the script.

If you do not set a stream block, sometimes latency will cause your PHP script to think there was no response, causing you to not receive data.

Also, use stream_get_contents to pull from the socket. This will grab by default the full buffer.

The correct way is to use socket_read, not stream_get_contests as someone else suggested.

Here is an example:

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

$result = socket_connect($sock, "10.197.24.40", "5000");

$request = '{ "request" : { "id" : "some_function_id",  "data": "55555555-5"} }';

// We send the request
socket_write($sock,$request);

socket_read($sock,1000000);

socket_close($sock);

I have tested this code in a live environment and it works correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM