PHP中的Websocket和Apache上的Ratchet

问题描述

我是WebSockets的新手,我有一个运行Apache的PHP host 主机,并在Websocket中使用了Ratchet库。当我尝试连接时,我无法连接到错误

这是JS代码

const conn = new WebSocket('wss://example.com/test/test.PHP');
console.log(conn);

conn.onopen = function () {
    console.log('Connected');
    conn.send(JSON.stringify({ message: 'hello' }));
}

conn.onmessage = function (e) {
    console.log(`New Message ${e.data}`);
}

conn.onclose = function () {
    console.log('Connection Closed');
}

以及JS连接的PHP代码

<?PHP
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;

require_once $_SERVER['DOCUMENT_ROOT'] . "/lib/vendor/autoload.PHP";
require_once $_SERVER['DOCUMENT_ROOT'] . "/src/classes/Socket.PHP";


$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Socket()
        )
    ),8888
);

$server->run();

如果需要Socket()类,请参见以下代码

<?PHP

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Socket implements MessageComponentInterface
{
    protected $connected_users;

    public function __construct()
    {
        $this->connected_users = new \SplObjectStorage;
    }

    public function onCall(ConnectionInterface $conn,$id,$topic,array $params)
    {
        //
    }


    public function onopen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $conn->send(json_encode(array("status" => "success")));
    }

    public function onMessage(ConnectionInterface $from,$msg)
    {
        $msg = json_decode($msg);
        // do something with the $msg

    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn,\Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...