在Windows 7命令行窗口中通过PHP套接字发送json数据

时间:2015-02-17 09:42:24

标签: php json sockets

我检查了一下 php sockets read json array from java server Sending configuration data to websocket 并花了一整天时间来寻找以下问题的解决方案。 我有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";
?>

和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;
    }

}

我使用的是Windows 7 atm,但应用程序将在命令行中的unix系统上运行。我打开2 cmd窗口并首先启动Server.php。我在第二个cmd窗口中启动Client.php。我收到以下错误(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.

当我发送字符串时没有问题。我如何处理json数据?

1 个答案:

答案 0 :(得分:1)

得到了解决方案。我需要发送json作为字符串,它工作。 下面的Client.php

$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

$jsonString = "";
        if(!socket_last_error($socket)){
            while($buffer=socket_read($connection,2048)){
               //echo $buffer;
               $jsonString.=$buffer;
            }
        }
echo $jsonString;

我希望它可以帮助某人并避免一些头痛。