我正在尝试Ratchet库使用位于http://socketo.me/的WebSockets,但在Ubuntu中从命令行运行服务器脚本时遇到一些问题。
在成功安装composer和Ratchet之后,我在http://socketo.me/docs/hello-world上遵循基本聊天应用程序的教程,我在运行它的步骤。我的文件结构,websockets是我的项目文件夹,是:
kingsconflict
websockets
chat.php
chat-server.php
composer.json
vendor
autoload.php
(dependecies included by composer for Ratchet)
当我输入"sudo php chat_server .php"时,我得到的错误是" php致命错误:require(): Failed opening required '/var/www/kingsconflict/vendor/autolload .php' (include_path='.:/usr/share/php:/usr/share/pear') in/var/www/kingsconflict/websockets/chat_server .php on line 5"。它似乎试图打开/var/www/kingsconflict/vendor/autolload .php,但实际路径是/var/www/kingsconflict/websockets/vendor/autolload .php,我不知道为什么它这样做。
chat-server.php
<?php
use Ratchet'Server'IoServer;
use MyApp'Chat;
require dirname(__DIR__) . '/vendor/autoload.php'; // Error here
$server = IoServer::factory(
new Chat()
, 8080
);
$server->run();
我试着用下面的行替换错误行,我停止得到错误,但我得到一个新的错误"PHP致命错误:类'MyApp'Chat'未找到",这让我相信这个修复是不对的。
require ('./vendor/autoload.php');
其他文件的代码与棘轮教程中显示的相同,但以防万一,我将把它们贴在
下面chat.php
<?php
namespace MyApp;
use Ratchet'MessageComponentInterface;
use Ratchet'ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new 'SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})'n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "'n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected'n";
}
public function onError(ConnectionInterface $conn, 'Exception $e) {
echo "An error has occurred: {$e->getMessage()}'n";
$conn->close();
}
}
composer.json
{
"autoload": {
"psr-0": {
"MyApp": "src"
}
},
"require": {
"cboden/Ratchet": "0.2.*"
}
}
autoload.php(没有编辑,但是管他呢)
<?php
// autoload.php generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit0964ef3a5e66723368300f04c3206ca1::getLoader();
假设您的作曲器。json是
{
"autoload": {
"psr-0": {
"MyApp": "src"
}
},
"require": {
"cboden/Ratchet": "0.3.*"
}
}
在启动bin/chat-server.php之前,你必须更新自动加载文件:
$ composer.phar update
你的问题是文件结构。仔细阅读本教程会发现,你的聊天类应该在/src/MyApp/chat .php中,而你的服务器脚本应该在/bin/chat-server.php中。
尝试先自动加载文件:
$ composer update
如果它仍然不起作用,那么包括require 'chat.php';
行,就在chat-server.php
文件的开头。