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

标签 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数据处理?

最佳答案

得到了解决方案。我需要将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;

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

关于php - 在Windows 7命令行窗口中通过PHP套接字发送JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28558872/

相关文章:

php - 如何使用 PHP 检查 HTML 表单是否为空

Java Socket 接收和发送数据 (JSON-RPC 2.0)

javascript - GoogleMaps 回调参数无效

php - Å 与 å 在 mysql 查询中不匹配 - 如何进行不区分大小写的匹配

php - MySQL Inner Join 查询给出错误

c++ - 创建一个Qstring的Json数组

从 json 对象检查 jquery radio 输入

python - 根据文本文件中的日期读取 block 中的数据 - python

C++ SFML UDP Socket 向多个客户端接收和发送数据

android - 维护双向 UDP 连接