2

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 ?

3
  • Is there a reason for not using a carrier protocol (HTTP eing the obvious choice)? Commented Feb 17, 2015 at 10:00
  • It will be local connection between DB and local computer. I found "AF_INET IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family." in php manual. Ultimately "AF_UNIX Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication)." will be used. I wanna test it on my machine first. Could you explain to me how I can use HTTP in this situation ? I will give it a go if viable. Thank you Commented Feb 17, 2015 at 10:09
  • This rather raises more questions than it answers (high efficiency and JSON aren't obvious bedfellows). But to answer your question - a REST server. Commented Feb 17, 2015 at 13:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.