$ conn-> WebSocket总是返回[“ closing”] => bool(false)

时间:2018-09-10 15:56:23

标签: php websocket ratchet

我正在尝试将Larchet与laravel一起使用,但是当我在onOpen或onMessage中对$ conn-> WebSocket进行var_dump时,它总是返回我

  

object(stdClass)#670(1){[“关闭”] => bool(false)}

这是我使用的代码

namespace App\Http\Controllers;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use App;
use Auth;
use Config;
use Crypt;
use App\User;
use Illuminate\Session\SessionManager;

class WebSocketController extends Controller implements MessageComponentInterface{
function onOpen(ConnectionInterface $conn){
$session = (new SessionManager(App::getInstance()))->driver();
var_dump($conn->WebSocket);
}

function onClose(ConnectionInterface $conn){
}

function onError(ConnectionInterface $conn, \Exception $e){
$conn->close();
}

function onMessage(ConnectionInterface $conn, $msg){
var_dump($conn->WebSocket);
}
}

1 个答案:

答案 0 :(得分:1)

我建议您使用一个名为Woketo的简单库,用于php中的websocket

  

作曲家需要“ nekland / woketo”

运行websocket服务器的最简单示例

您的websocket服务器

use Your\Namespace\YourMessageHandler;
use Nekland\Woketo\Server\WebSocketServer;

$server = new WebSocketServer(1337);
$server->setMessageHandler(new YourMessageHandler(), '/path'); // accessible on ws://127.0.0.1:1337/path
$server->start();

您的处理程序类,在这里您可以从客户端检索数据或向客户端发送数据

 <?php
    // YourMessageHandler.php

    namespace Your\Namespace;

    use Nekland\Woketo\Core\AbstractConnection;
    use Nekland\Woketo\Message\TextMessageHandler;

    class YourMessageHandler extends TextMessageHandler
    {
        public function onConnection(AbstractConnection $connection)
        {
            // Doing something when the client is connected ?
            // This method is totally optional.
        }

        public function onMessage(string $data, AbstractConnection $connection)
        {
            // Print the message received from the connection
            var_dump($data);
            // Sending back the received data
            $connection->write($data);
        }
    }

在安装过程中随时询问您是否有问题