Sending json data through PHP sockets in Windows 7 command line windows - php

I checked
php sockets read json array from java server
Sending configuration data to websocket
and spent all day on finding the solution for the following problem.
I have Client.php
<?php
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
//Connect socket to remote server
if(!socket_connect($sock , '127.0.0.1', 23))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not connect: [$errorcode] $errormsg \n");
}
echo "Connection established \n";
$data = file_get_contents ("C:\Users\(myUsername here)\Desktop\sockets\Test.txt");
$json = json_decode($data, true);
echo $data . " this is data from file\n";
echo $json . " this is decoded version\n";
echo json_encode($data) . " this is encoded version\n";
$jsonSer = serialize($json);
//socket_write($sock, count($json). "\n\r");
socket_write($sock, $jsonSer);
echo $jsonSer . " this is serialized version\n";
echo unserialize($jsonSer) . " this is unserialized message\n";
//Send the message to the server
//$sock , $message , strlen($message) , 0
//JSON.stringify(data)
if( ! socket_send($sock, $jsonSer, 1024, 0))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n\r");
}
echo "Message send successfully \n";
?>
And Server.php
<?php
// we create the socket (domain, type, protocol)
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
// AF_UNIX
// if false we pass error code to strerror to get a textual explanation of the error
// and exit execution of the code
if (!$socket) {
echo "Couldn't create socket";
exit(socket_strerror(socket_last_error()));
}
echo "Socket created.\n";
//$address = '127.0.0.1';
//$port = '23';
// we bind the name given in address to the socket
$socket_bound = socket_bind ($socket , '127.0.0.1', 23);
if (!$socket_bound) {
echo "Couldn't bind socket";
exit(socket_strerror(socket_last_error()));
}
echo "Socket bound.\n";
// we tell the socket to listen for incoming connections on socket and keep them in
// backlog (e.g. 25)
$backlog = 25;
$socket_is_listening = socket_listen($socket, $backlog);
if (!$socket_is_listening) {
echo "Socket is not listening";
exit(socket_strerror(socket_last_error()));
}
echo "Socket is listening...\n";
// we set socket to be non-blocking in order to fork connections
socket_set_nonblock($socket);
echo "Waiting for connections...\n";
$server_is_listening = true;
while($server_is_listening) {
// Accept incoming connection
$connection = socket_accept($socket);
if (!$connection){
// we check every 100ms for new connections
usleep(100);
}elseif($connection>0){
// fork connections
// update connections progress and tell the user
// parse json to php object or array (2nd para = 1)
//$database_data_php = json_decode($database_data_json,0);
// accept incoming connection
/* //display information about the client who is connected
if(socket_getpeername($client , $address , $port))
{
echo "Client $address : $port is now connected to us.";
}*/
$response = "Amazing, server responded";
echo "Yay !!! We have a connection\n";
if(socket_getpeername($connection , $address , $port))
{
echo "Client $address : $port is now connected to us. \n";
echo "Connection is: $connection\n";
}
//Now receive reply from server
/*socket_recv ( $connection , $data , 2045 , MSG_WAITALL )*/
//socket_read($connection, 512, PHP_NORMAL_READ);
$input = socket_read($socket, $spawn, 1024);
echo $input . " INPUT";
$buffer = socket_recv($socket, $dataIn, 1024, 0);
echo $buffer . " buffer";
if(!socket_recv($socket, $dataIn, 1024, MSG_WAITALL)){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
//print the received message
$response = unserialize($dataIn);
echo $dataIn;
//echo $buff;
socket_write($connection, $response);
//socket_close($connection);
}else{
echo "Error: ".socket_sterror($connection);
die;
}
}
I use windows 7 atm but the app will be run on unix system in command line. I open 2 cmd windows and start Server.php in first. I start Client.php in the second cmd window. I get the following errors (Server.php).
Socket created.
Socket bound.
Socket is listening...
Waiting for connections...
Yay !!! We have a connection
Client 127.0.0.1 : 50162 is now connected to us.
Connection is: Resource id #5
C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 70
PHP Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 72
Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 72
PHP Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 75
Warning: socket_recv(): unable to read from socket [0]: The operation completed successfully.
in C:\Users\(myUsername here)\Desktop\sockets\Server.php on line 75
Could not receive data: [0] The operation completed successfully.
When I sent a string there was no problem. How do I have proceed with json data please ?

Was given the solution. I need to send json as string and it worked.
Client.php below
$jsonString = "";
$handle = fopen("C:\Users\(myUsername)\Desktop\sockets\Test.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer."\n";
//echo gettype($buffer)." buffer inside";
$jsonString.=$buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
}
socket_write($sock, $jsonString);
fclose($handle);
Server.php below
$jsonString = "";
if(!socket_last_error($socket)){
while($buffer=socket_read($connection,2048)){
//echo $buffer;
$jsonString.=$buffer;
}
}
echo $jsonString;
I hope it can help someone and save some headache.

Related

php UDP socket listener on windows

I want to make udp listener on windows but I failed to do so, I tried couple of codes which available online but it didn't work for me, it seems that my windows php configuration is not done properly so code is not able to connect to socket, the code keeps waiting for messages but it receive nothing, I tested my network using two PCs with ready UDP sender/receiver app, and it works fine,
please check my code below and the output, please let me know if I should do something in php.ini
<?php
//Reduce errors
error_reporting(~E_WARNING);
//Create a UDP socket
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if( !socket_bind($sock, "127.0.0.1" , 1235) )
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
//Do some communication, this loop can handle multiple clients
while(1)
{
echo "Waiting for data ... \n";
//Receive some data
$r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
echo "$remote_ip : $remote_port -- " . $buf;
//Send back the data to the client
socket_sendto($sock, "OK " . $buf , 100 , 0 , $remote_ip , $remote_port);
}
socket_close($sock);
cmd php code with output

php socket server works only on localhost but not live server

I have hosting domain godaddy and i enabled socket module, but dose not work
this code works only in localhost when i upload it in server it does not work.
code server.php
<?php
// set some variables
$host = '150.113.178.20';
$port = 5000;
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if( !socket_bind($sock, $host , $port) )
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
if(!socket_listen ($sock , 10))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
echo "Socket listen OK \n";
echo "Waiting for incoming connections... \n";
//start loop to listen for incoming connections
while (true)
{
//Accept incoming connection - This is a blocking call
$client = socket_accept($sock);
//display information about the client who is connected
if(socket_getpeername($client , $address , $port))
{
echo "Client $address : $port is now connected to us. \n";
}
//read data from the incoming socket
$input = socket_read($client, 1024000);
$response = "OK .. $input";
// Display output back to client
socket_write($client, $response);
}
when i execute server.php script in ssh no problem
but when i write from CMD :
Error log file
After some research i found that The code is correct
Godaddy does not open custom ports.
The code does not work because have a different security policy localhost than GoDaddy (or other hosting website).

Reading UDP Packets from PHP with my browser

I tried to make a php script to reading udp packets from browser but I just make one that only I can use it with cmd with ( php filename.php ), my question is how I can read the same way from my browser to get packets!
my php script I use:
<?php
//Reduce errors
error_reporting(~E_WARNING);
//Create a UDP socket
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if( !socket_bind($sock, "127.0.0.1" , 2223) )
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
//Do some communication, this loop can handle multiple clients
while(1)
{
echo "Waiting for data ... \n";
//Receive some data
$r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
echo $buf;
//echo "$remote_ip : $remote_port -- " . $buf;
//Send back the data to the client
//socket_sendto($sock, "OK " . $buf , 100 , 0 , $remote_ip , $remote_port);
}
socket_close($sock);
?>

Receive Java Socket in PHP

I've got the following problem:
I just created a new Socket connection and told my mediaRecorder to send its recorded data via socket:
Socket soc=null;
try {
soc = new Socket("192.168.178.103",8888);
Log.i(TAG, "Connected to socket");
} catch (Exception e) {
}
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(soc);
myCamera = getCameraInstance();
mediaRecorder = new MediaRecorder();
myCamera.unlock();
mediaRecorder.setCamera(myCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
mediaRecorder.setOutputFile(pfd.getFileDescriptor());
.
.
.
I have the following php test code from http://www.binarytides.com/udp-socket-programming-in-php/:
<?php
//Reduce errors
error_reporting(~E_WARNING);
//Create a UDP socket
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if( !socket_bind($sock, "192.168.178.103" , 8888) )
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
//Do some communication, this loop can handle multiple clients
while(1)
{
echo "Waiting for data ... \n";
//Receive some data
$r = socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
echo "$remote_ip : $remote_port -- " . $buf;
//Send back the data to the client
socket_sendto($sock, "OK " . $buf , 100 , 0 , $remote_ip , $remote_port);
}
socket_close($sock);
I just tested around when i just write something like "procedured" in a file when my index.php on the server side is called. It works, but with this code my socket does not receive any data.
Do you have a clue for me?
Thank you!

PHP Socket Disconnecting Randomly

I'm using a PHP Socket to listen on port 6000 for incoming connections and its working perfectly 99% percent of the time but 1% of the time the client is getting a connection error when sending a request to the server. I created a different script to ping the socket on port 6000 every second in an infinite loop and write the result to a log file so I can see if its breaking, and out of 78,000 Successful pings, 23 Failed.
There must be some small logic error with my code which is causing this. If anyone has any ideas its much appreciated.
Socket:
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if( !socket_bind($sock, "0.0.0.0" , 6000) )
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
if(!socket_listen ($sock , 10))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
echo "Socket listen OK \n";
echo "Waiting for incoming connections... \n";
//start loop to listen for incoming connections
while (true)
{
//Accept incoming connection - This is a blocking call
$client = socket_accept($sock);
//read data from the incoming socket
$input = "";
$input = socket_read($client, 10000000);
if ($input != "")
{
// do my logic here with $input
}
}
socket_close($sock);
EDIT: No, I'm not using CMD to ping. This is my PHP script which is doing the pinging:
<?php
$host = '0.0.0.0';
$port = 6000;
$waitTimeoutInSeconds = 1;
while(true)
{
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds))
{
$file = 'log.txt';
$current = file_get_contents($file);
$today = date("Y-m-d_H:i:s");
$current .= $today . " - SUCCESS\n";
file_put_contents($file, $current);
}
else
{
$file = 'log.txt';
$current = file_get_contents($file);
$today = date("Y-m-d_H:i:s");
$current .= $today . " - FAILED\n";
file_put_contents($file, $current);
}
fclose($fp);
sleep(1);
}
?>
For an actual transaction, the client is only connected for a split second while it sends through an xml request in raw text, then it does some logic which takes less than a second. Since its failing on the ping test though, that means my listener is breaking for a second for one reason or another does it not?
I'm not sure if I understand correctly.
You say about 0,03% of your pings failed. Is this your problem? If these are real pings (ping.exe from cmd.exe) then it has nothing to do with your logic. It's the network. (Is the host on WIFI?)
If you are convinced it's your logic:
If someone connects, how long is he connected? And what happens to new requests while connected to the previous client? I think you may find your answer here.
Also try to do a test with a client that continuously connects and sends dummy data, in stead of pinging. And log what responses the client is receiving.

Categories