我正在尝试使用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():无法打开所需的'/var/www/kingsconflict/vendor/autoload.php'(include_path ='。 :/ usr / share / php:/ usr / share / pear')在/var/www/kingsconflict/websockets/chat-server.php第5行“。好像它正在尝试打开/var/www/kingsconflict/vendor/autoload.php,但实际的路径是/var/www/kingsconflict/websockets/vendor/autoload.php,我不知道为什么会这样做。
聊天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');
其他文件的代码与Ratchet教程中显示的相同,但万一我将在下面发布
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();
答案 0 :(得分:16)
假设你的composer.json是
{
"autoload": {
"psr-0": {
"MyApp": "src"
}
},
"require": {
"cboden/Ratchet": "0.3.*"
}
}
在启动bin / chat-server.php之前,您必须使用以下命令更新自动加载文件:
$ composer.phar update
答案 1 :(得分:9)
您的问题是您的文件结构。仔细阅读教程会发现您的聊天类应该在/src/MyApp/Chat.php中,而您的服务器脚本应该在/bin/chat-server.php中。
答案 2 :(得分:1)
首先尝试自动加载文件:
$ composer update
如果仍然无效,请在require 'chat.php';
文件的开头添加行chat-server.php
。它对我有用。