如何使用PHP和Ratchet创建websocket?

时间:2017-02-01 00:18:08

标签: javascript php sockets ratchet

我一直试图使用PHP创建一个Ratchet Web套件很长一段时间没有成功。我在Github页面和Ratchet网站上引用了文档。有没有人知道更好的文档,或者,如果你有经验,你能解释我如何创建一个基本的Web套接字?谢谢。

我正在使用Ubuntu Mate 16.04和一个使用PHP的在线实时Apache Web服务器。这就是我尝试过的:

  • 安装棘轮与作曲家
  • 在/ var / www / html / webSocket /
  • 中创建了一个html页面和PHP Web套接字服务器页面

这就是chat-server-socket-test.php的样子:

<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

    // Make sure composer dependencies have been installed
    require __DIR__ . '/vendor/autoload.php';

/**
 * chat.php
 * Send any incoming messages to all connected clients (except sender)
 */
class MyChat implements MessageComponentInterface {
    protected $clients;

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

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        foreach ($this->clients as $client) {
            if ($from != $client) {
                $client->send($msg);
            }
        }
    }

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

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

    // Run the server application through the WebSocket protocol on port 8080
    $app = new Ratchet\App('localhost', 8080);
    $app->route('/chat', new MyChat);
    $app->route('/echo', new Ratchet\Server\EchoServer, array('*'));
    $app->run();
?>

这就是我的HTML页面:

<!DOCTYPE HTML>
<html>
<head>
<script>
// Then some JavaScript in the browser:
    var conn = new WebSocket('ws://williamgreen.hopto.org/webSocket/chat-server-socket-test.php:8080/echo');
    conn.onmessage = function(e) { console.log(e.data); };
    conn.send('Hello Me!');
</script>
</head>
<body>
<h1>web socket</h1>
</body>
</html>

这是我在网络浏览器控制台中收到的错误:

  

未捕获DOMException:无法在'WebSocket'上执行'send':仍然   在连接状态。       在http://williamgreen.hopto.org/webSocket/test.html:8:10

     

WebSocket连接到   'WS://williamgreen.hopto.org/webSocket/chat-server-socket-test.php:8080 /回声   失败:WebSocket握手期间出错:意外的响应代码:   404

有什么想法吗?

0 个答案:

没有答案