yii 运行Ratchet 包的websocket

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测试连接
不细说
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值