Roi*_*Roi 5 javascript php websocket composer-php ratchet
我是这个websocket的初学者,我正在为我的第一个项目尝试这个棘轮.
我已经在http://socketo.me中通过在命令提示符中执行此命令完成了安装教程
composer require cboden/ratchet
之后,它会自动生成vendor一个包含几个库的文件夹,并在主路径a composer.json和composer.lock
然后我创建了一个chat.php文件并从棘轮git上的快速示例中复制了代码:
<?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();
Run Code Online (Sandbox Code Playgroud)
然后我在命令提示符下执行此命令: php chat.php
我的客户端仍然有错误说:
铬
Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
火狐
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
我的folderization(在XAMPP上):
客户
htdocs/public/chat/index.php一个common.js完整的包含
var conn = new WebSocket('ws://localhost:8080/echo');
conn.onmessage = function(e) { console.log(e.data); };
conn.send('Hello Me!');
Run Code Online (Sandbox Code Playgroud)
服务器
htdocs/public/chatserver/chat.php
htdocs/public/chatserver/vendor/<some libraries>
htdocs/public/chatserver/composer.json
htdocs/public/chatserver/composer.lock
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
请试试这样:
var conn = new WebSocket('ws://localhost:8080/echo');
conn.onmessage = function(e) { console.log(e.data); };
conn.onopen = function(e) {
console.log("Connection established!");
conn.send('Hello Me!');
};
Run Code Online (Sandbox Code Playgroud)
您应该能够在连接打开时发送.似乎是在建立连接之前尝试它的情况.
| 归档时间: |
|
| 查看次数: |
9352 次 |
| 最近记录: |