Reputation: 479
This Is my code to connect java socket :-
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, '127.0.0.1', 12345);
while(true)
{
// read a line from the socket
$line = socket_read($socket, 1024, PHP_NORMAL_READ);
var_dump($line);
$someArray = json_decode($line, true);
$otp = $someArray["otp"];
if($someArray["msg"] == "otp_generation")
{
$myObj = new \stdClass();
$myObj->msg = "OTP RECEIVED NEED TO CONNECT";
$send = json_encode($myObj);
socket_send($socket, $send, strlen($send), 0);
}
exit;
}
My Question is -
When connection is established successfully server send one OTP to client and received successfully in client. Then i send data to server OTP RECEIVED acknowledgement, it also received in server. After OTP RECEIVED acknowledgement server send welcome msg to client. I cant get the welcome message. if i remove the "exit" code browser is still loading, finally crashing. Why i didn't receive the second data. anyone solve my issue. what i need to modify. am beginner for socket.
I need to display Welcome msg. What can i do?
Upvotes: 0
Views: 119
Reputation: 479
Without new line cmd data is not send. This is the mistake i done. Finally i got the answer from my friend.
I just add the line below;-
socket_send($socket, $send."\r\n", strlen($send."\r\n"), 0);
Thanks @hemanth kumar and @Barmar
Upvotes: 0
Reputation: 780974
You need to continue looping and read the next message, then break out of the loop.
while(true)
{
// read a line from the socket
$line = socket_read($socket, 1024, PHP_NORMAL_READ);
var_dump($line);
$someArray = json_decode($line, true);
if($someArray["msg"] == "otp_generation")
{
$otp = $someArray["otp"];
$myObj = new \stdClass();
$myObj->msg = "OTP RECEIVED NEED TO CONNECT";
$send = json_encode($myObj);
socket_send($socket, $send, strlen($send), 0);
} elseif ($someArray["msg"] == "welcome") {
// do whatever you need to do with the rest of the message
break; // then get out of the loop
} else {
echo "Unknown message received";
var_dump($someArray);
break;
}
}
I had to make a guess about how the welcome message is formatted, but this should give you the general idea.
Upvotes: 1