我尝试运行Websocket服务器,但是由于某种原因我无法弄清楚它无法运行。我使用了本教程:http://socketo.me/docs/hello-world
我有这个主文件夹:enter image description here
composer.js:
{
"autoload": {
"psr-4": {
"dealspace_websocket\\": "websocket_src"
}
},
"require": {
"cboden/ratchet": "^0.4.2"
}
}
在websocket_src
文件夹内,只有1个文件,Chat.php:
<?php
namespace dealspace_websocket;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
require_once __DIR__ . "/../Model/DBConnection.php";
class Chat 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) {
$JSonMsg = json_decode($msg);
if($JSonMsg['type'] === 'updownvote') {
$connection = new DBConnection();
$allowUpdate = false;
try {
$sql = 'UPDATE `deals`
SET `votes_counter` = :vc
WHERE `id` = :id';
$stmt = $connection->dbh->prepare($sql);
$allowUpdate = $stmt->execute(array(
'vc' => $JSonMsg['data']['votes'],
'id' => $JSonMsg['data']['dealid']
));
if($allowUpdate !== false) {
$dataOBJ->dealid = $JSonMsg['data']['dealid'];
$dataOBJ->votes = $JSonMsg['data']['votes'];
$returnMsg->type = 'updownvote';
$returnMsg->date = $dataOBJ;
foreach($this->clients as $client) {
$client->send(json_encode($returnMsg));
}
}
} catch(PDOException $e) {}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
以及最后一个文件,websocket_server.php:
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use dealspace_websocket\Chat;
require __DIR__ . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
?>
然后,当我在主文件夹中打开CMD时,运行:php websocket_server.php
这是结果:enter image description here
为什么?
您正在require
-类别后正在vendor/autoload.php
-use
文件。
将require __DIR__ . '/vendor/autoload.php';
放在文件顶部,PHP将可以找到这些类。
<?php
require __DIR__ . '/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use dealspace_websocket\Chat;
编辑
还有一个我起初没有注意到的关键部分,它是composer.json
中的错别字,您需要在namespace指向的路径前面加上/
来告诉作曲家看给定目录下的文件。
结果json
为:
"psr-4": {
"dealspace_websocket\\": "websocket_src/"
}
进行此更改后,请运行composer dump-autoload
您可以阅读有关PSR-4自动加载
composer dump-autoload
和here的更多信息。