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?
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.
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
Related
I am writing a client app that is connecting to a telnet server. Both client and server are on a raspberry pi. I need to send multiple commands to the server and the send is going through properly but the return is coming back empty after the first send command
$message1 = "get a";
$message2 = "get b";
socket_write ($socket , $message1, strlen($message1));
// get server response
$line = socket_read($socket,8192,PHP_NORMAL_READ);
//Parse json return
$json = json_decode($line, true);
$a = $json["request_id"];
echo $a;
sleep(2);
socket_write ($socket , $message2, strlen($message2));
// get server response
$line2 = socket_read($socket,8192,PHP_NORMAL_READ);
//Parse json return
$json = json_decode($line2, true);
$b = $json["request_other_id"];
echo $b;
echo $a is returning data but echo $b is empty. Looking at the server logs, the command for $message2 is flagged as a success
echo $line2 is also returning blank
I'm working on a Server list viewer
and somebody told me that i should use UdpSocket to send data to the master server and receive data from it (in this case for MW2-IW4 game)
So this is the command or the socket you use
"\xff\xff\xff\getservers IW4 <MASTERSERVERPORTHERE> full empty\x00"
so i tried to work with this code
<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$msg = "\xff\xff\xff\getservers IW4 <MASTERSERVERPORT> full empty\x00";
$len = strlen($msg);
socket_sendto($sock, $msg, $len, 0, 'MASTERSERVERIP' , 1223);
socket_close($sock);
?>
but didn't receive any data , just getting the number 36 ...
PS:
i don't know much things about sockets.
i figured out how to do it a while ago and remembered this post, if anybody is still interested, this is how you do it:
<?php
$ip = "127.0.0.1";
$port = 1337;
$socket = fsockopen('udp://'.$ip, $port);
stream_set_blocking($socket, 0);
stream_set_timeout($socket, 1); //1 = timeout
fwrite($socket, "YOUR UDP COMMAND HERE\n");
$time=time()+1; //1=timeout
$returned = "";
while($time > time()) {
$returned .= fgets($socket);
}
echo($returned); // the returned value
#fclose($socket); //we are done, so better close it.
?>
Just use fsockopen it's a lot easier,
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) echo "ERROR: $errno - $errstr<br />\n";
fwrite($fp, "\n");
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
Im opening up a connection to a server that accepts XML requests. I am required to send two requests one after the other.
If I run the first request on its own I get data back
If I run the second request on its own I get data back
If I run both within a loop using the same connection, only the first request works, the second returns no data.
Is there something I need to send to the socket between each request to indecate the end of each request, otherwise what am I doing wrong?
// Open socket connection
$socket = pfsockopen($this->config['ip'], $this->config['port'], $errno, $errstr, 30);
// Try and open a connection
if ( ! $socket) {
throw new \Exception($errstr . '('.$errno.')');
}
// If connection was successfull start sending requests
else{
// Loop each request within the container
foreach($this->container as $key => $object){
print "Request" . ($key+1) . PHP_EOL;
// Reset data and post string
$data = array();
$xml_post_string = null;
// Create XML string
$xml = \LSS\Array2XML::createXML('request', $object->request);
$xml_post_string = $xml->saveXML();
// Add ending lines
$xml_post_string = $xml_post_string . PHP_EOL . PHP_EOL;
// Loop
fwrite($socket, $xml_post_string);
while ( ! feof($socket)) {
$data[] = fgets($socket, 1024);
}
// Tried adding, but fails
ftruncate($socket, 2);
if(count($data)){
print implode($data);
}
else{
print "No response from server - you broke it" . PHP_EOL;
}
}
}
fclose($socket);
A second attempt. The results are the same for any random server out there.
// Create a TCP/IP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// Connect the socket
socket_connect($socket, 'xxx.xxx.xxx.xxx', '80');
$xml_post_string_one = '<request><message>Hello first world</message></request>';
$xml_post_string_two = '<request><message>Hello second world</message></request>';
// FIRST ROUND //
// Send data to it
socket_write($socket, $xml_post_string_one, strlen($xml_post_string_one));
// Get data from it
socket_recv($socket, $bufA, 2048, MSG_WAITALL);
// Done
print strlen($bufA) . PHP_EOL; // Got info back
// SECOND ROUND //
// Send data to it
socket_write($socket, $xml_post_string_two, strlen($xml_post_string_two));
// Get data from it
socket_recv($socket, $bufB, 2048, MSG_WAITALL);
// Done
print strlen($bufB). PHP_EOL; // Returns 0, Why?
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.
We're using a system at the moment that takes an incoming JSON request over TCP and responds using JSON too. Currently I've set up my socket like so in PHP:
$socket = fsockopen($host, $port, $errno, $errstr, $timeout);
if(!$socket)
{
fwrite($socket, $jsonLoginRequest); // Authentication JSON
while(json_decode($loginResponse) == false) // We know we have all packets when it's valid JSON.
{
$loginResponse .= fgets($socket, 128);
}
// We are now logged in.
// Now call a test method request
fwrite($socket, $jsonMethodRequest);
while(json_decode($methodResponse) == false) // We know we have all packets when it's valid JSON.
{
$methodResponse .= fgets($socket, 128);
echo $methodResponse; // print response out
}
// Now we have the response to our method request.
fclose($socket);
}
else
{
// error with socket
}
This works at the moment, and the server responds to the method request. However, some methods will respond like this to acknowledge the call, but will also respond later on with the results I'm after. So what I really need is a TCP listener. Could anyone advise how I could write a TCP listener using fsock like I have above?
Thanks
To create a listening socket use the following functions:
socket_create_listen (this one is cool)
socket_accept
I'm not shure if fwrite()/fread() are working with those sockets otherwise you have to use the following functions:
socket_recv
socket_send
Message-loop
I have now written some function to read a single JSON responses with the assumption that multiple responses are separated by CRLF.
Here's how I would do it (assuming your php-script has unlimited execution time):
// ... your code ...
function readJson($socket) {
$readData = true;
$jsonString = '';
while(true) {
$chunk = fgets($socket, 2048);
$jsonString .= $chunk;
if(($json = json_decode($jsonString)) !== false) {
return $json;
} elseif(empty($chunk)) {
// eof
return false;
}
}
}
// ....
// Now call a test method request
fwrite($socket, $jsonMethodRequest);
$execMessageLoop = true;
while($execMessageLoop) {
$response = readJson($socket);
if($response === false) {
$execMessageLoop = false;
} else {
handleMessage($socket, $response);
}
}
function handleMessage($socket, $response) {
// do what you have to do
}
Now you could implement the "handleMessage" function which analyses the response and acts to it.