swoft之ws的使用

配置

    'wsServer'           => [
        'class'    => WebSocketServer::class,
        'port'     => 18308,
        'listener' => [
            // 'rpc' => bean('rpcServer'),
            // 'tcp' => bean('tcpServer'),
        ],
        'on'       => [
            // ws默认支持http请求
            // Enable http handle
            SwooleEvent::REQUEST => bean(RequestListener::class),
            // Enable task must add task and finish event
            SwooleEvent::TASK    => bean(TaskListener::class),
            SwooleEvent::FINISH  => bean(FinishListener::class)
        ],
        'debug'    => 1,
        // 'debug'   => env('SWOFT_DEBUG', 0),
        /* @see WebSocketServer::$setting */
        'setting'  => [
            'task_worker_num'       => 6,
            'task_enable_coroutine' => true,
            'worker_num'            => 6,
            'log_file'              => alias('@runtime/swoole.log'),
            // 'open_websocket_close_frame' => true,
        ],
    ],

启动

【ws默认支持http请求,http请求的端口和ws端口都是 18308】

php swoftcli.phar run -c ws:start -b bin/swoft -d

 

前端请求代码

    // 建立链接,这里请求的是swoft-ws的chat模型
    new WebSocket('ws://192.168.0.155:18308/chat')

    // swoft接收的数据格式
    var send = {
        "cmd": route, // 请求控制器的路由名
        "data": {     // 发送自定义的数据
          "msg" : send_msg,
          "callback" : {
            "active": fn,
            "param" : param
          }
        },
    }
    // json转字符串
    send = JSON.stringify(send)
    // 发送
    ws.send(send)

 

swoft的目录结构

 

ws控制器路由注解

namespace App\WebSocket\Chat;

use Swoft\Session\Session;
use Swoft\WebSocket\Server\Annotation\Mapping\MessageMapping;
use Swoft\WebSocket\Server\Annotation\Mapping\WsController;
use Swoft\Redis\Redis;
use App\WebSocket\Chat\BaseController;
use Swoft\Db\DB;

/**
 * Class HomeController
 *
 * @WsController()
 */
class HomeController extends BaseController
{
    /**
     * Message command is: 'home.index'
     *
     * @return void
     * @MessageMapping()
     */
    public function index(): void
    {
        // Session::current()->push('hi, this is home.index');

        // 给指定客户端发送消息
        // \server()->sendTo($fd, '给指定客户端发送消息');
        // 给指定部分客户端发送消息
        // \server()->sendToSome('给指定部分客户端发送消息', [$fd0, $fd1]);
        // 给所有人发送消息
        \server()->sendToAll('给所有人发送消息');
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值