1.安装composer
composer中国镜像
貌似需要php7.2以上
2.安装Ratchet
Ratchet
安装成功的话(成功安装系统环境变量)就可以在控制台任意地方用
composer 命令查看版本
3.在项目里新建composer.json文件
{
"name": "vendor_name/include",
"description": "description",
"minimum-stability": "stable",
"license": "proprietary",
"authors": [
{
"name": "咔咔",
"email": ""
}
],
"autoload": {
"psr-4": {
"MyApp\\": "WebSocketServer"
}
},
"require": {
"cboden/ratchet": "~0.4.4"
}
}
WebSocketServer为chet模型所在文件夹
在composer.json同级目录下运行控制台命令
composer install
会生成vendor目录
4.创建 项目根目录/WebSocketServer/Chet.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();
}
}
项目根目录/WebSocketServer/chet-server.php 脚本
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
6.运行脚本前先运行命令
composer dump-autoload
不让会报错Fatal error: Uncaught Error: Class ‘MyApp\Chat’ not found in
使用控制台运行命令
php WebSocketServer/chat-server.php
或者直接使用phpstromIDE的集成环境 运行chat-server.php
7.可以用postman测试连接
不细说