简言 2018-03-05 09:59:23 8799次浏览 3条评论 5 0 0

项目地址

https://github.com/jianyan74/yii2-websocket

Yii2 WebSocket

可以做即时通讯,小程序的小游戏等等

前提

服务器安装swoole

 git clone https://github.com/swoole/swoole-src.git
 cd swoole-src
 phpize
 ./configure --enable-openssl -with-php-config=[PATH] #注意[PATH]为你的php地址 开启ssl用
 make && make install

安装

composer执行

composer require "jianyan74/yii2-websocket"

或者在 composer.json 加入

"jianyan74/yii2-websocket": "^1.0"

配置

console/config/main.php 加入以下配置。(注意:配置在controllerMap里面)

// webSocket
'websocket' => [
    'class' => 'jianyan\websocket\WebSocketController',
    'server' => 'jianyan\websocket\WebSocketServer',
    'host' => '0.0.0.0',// 监听地址
    'port' => 9501,// 监听端口
    'config' => [// 标准的swoole配置项都可以再此加入
        'daemonize' => false,// 守护进程执行
        'ssl_cert_file' => '',
        'ssl_key_file' => '',
        'pid_file' => __DIR__ . '/../../backend/runtime/logs/server.pid',
        'log_file' => __DIR__ . '/../../backend/runtime/logs/swoole.log',
        'log_level' => 0,
    ],
],

使用

  # 启动 
  php ./yii websocket/start
  # 停止 
  php ./yii websocket/stop
  # 重启 
  php ./yii websocket/restart

测试

<script>
    var wsl = 'wss://[to your IP]:9501';
    ws = new WebSocket(wsl);// 新建立一个连接
    // 如下指定事件处理
    ws.onopen = function () {
        // ws.send('Test!');
    };
    // 接收消息
    ws.onmessage = function (evt) {
        console.log(evt.data);
        /*ws.close();*/
    };
    // 关闭
    ws.onclose = function (evt) {
        console.log('WebSocketClosed!');
    };
    // 报错
    ws.onerror = function (evt) {
        console.log('WebSocketError!');
    };
</script>
  • 评论于 2018-10-17 14:08 举报

    大佬用不了啊

    1 条回复
    评论于 2018-10-18 10:27 回复

    为什么用不了

  • 评论于 2019-04-22 16:25 举报

    Use of undefined constant SWOOLE_BASE这个错是什么鬼

    4 条回复
    评论于 2019-04-23 08:51 回复

    你swoole没有安装

    评论于 2019-04-23 09:39 回复

    安装后一样报这个错误

    评论于 2019-04-23 09:40 回复

    Author Swoole Team team@swoole.com
    Version 4.3.3
    Built Apr 23 2019 09:16:40
    coroutine enabled
    epoll enabled
    eventfd enabled
    signalfd enabled
    cpu_affinity enabled
    spinlock enabled
    rwlock enabled
    sockets enabled
    openssl OpenSSL 1.1.1 11 Sep 2018
    http2 enabled
    pcre enabled
    zlib enabled
    mutex_timedlock enabled
    pthread_barrier enabled
    futex enabled
    mysqlnd enabled
    async_redis enabled

    评论于 2019-04-23 10:18 回复

    https://github.com/jianyan74/yii2-websocket 最新的文档说明,我之前用的是swoole2.x

  • 评论于 2019-08-01 18:10 举报

    Could not open input file: ./yii 是咋回事

您需要登录后才可以评论。登录 | 立即注册