Hyperf使用WebSocket 服务

1.安装服务

composer require hyperf/websocket-server

2.配置 Server

修改 config/autoload/server.php,增加以下配置。

<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
use Hyperf\Server\Event;
use Hyperf\Server\Server;
use Swoole\Constant;

return [
    'mode' => SWOOLE_PROCESS,
    'servers' => [//监听多个端口
        [
            'name' => 'http',
            'type' => Server::SERVER_HTTP,
            'host' => '0.0.0.0',
            'port' => 9501,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
            ],
        ],
        [
            'name' => 'http',
            'type' => Server::SERVER_HTTP,
            'host' => '0.0.0.0',
            'port' => 9508,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'],
            ],
        ],
        [
            'name' => 'ws',
            'type' => Server::SERVER_WEBSOCKET,
            'host' => '0.0.0.0',
            'port' => 9502,
            'sock_type' => SWOOLE_SOCK_TCP,
            'callbacks' => [
                Event::ON_HAND_SHAKE => [Hyperf\WebSocketServer\Server::class, 'onHandShake'],
                Event::ON_MESSAGE => [Hyperf\WebSocketServer\Server::class, 'onMessage'],
                Event::ON_CLOSE => [Hyperf\WebSocketServer\Server::class, 'onClose'],
            ],
        ],
    ],
    'settings' => [
        Constant::OPTION_ENABLE_COROUTINE => true,
        Constant::OPTION_WORKER_NUM => swoole_cpu_num(),
        Constant::OPTION_PID_FILE => BASE_PATH . '/runtime/hyperf.pid',
        Constant::OPTION_OPEN_TCP_NODELAY => true,
        Constant::OPTION_MAX_COROUTINE => 100000,
        Constant::OPTION_OPEN_HTTP2_PROTOCOL => true,
        Constant::OPTION_MAX_REQUEST => 100000,
        Constant::OPTION_SOCKET_BUFFER_SIZE => 2 * 1024 * 1024,
        Constant::OPTION_BUFFER_OUTPUT_SIZE => 2 * 1024 * 1024,
    ],
    'callbacks' => [
        Event::ON_WORKER_START => [Hyperf\Framework\Bootstrap\WorkerStartCallback::class, 'onWorkerStart'],
        Event::ON_PIPE_MESSAGE => [Hyperf\Framework\Bootstrap\PipeMessageCallback::class, 'onPipeMessage'],
        Event::ON_WORKER_EXIT => [Hyperf\Framework\Bootstrap\WorkerExitCallback::class, 'onWorkerExit'],
    ],
];

3.配置路由(目前暂时只支持配置文件的模式配置路由,后续会提供注解模式。)

在 config/routes.php 文件内增加对应 ws 的 Server 的路由配置,这里的 ws 值取决于您在 config/autoload/server.php 内配置的 WebSocket Server 的 name 值。

/**
 * WebSocket相关的路由(目前只支持文件配置设置路由,注解版的目前官方还没有-20230517)
 */
Router::addServer('ws', function () {
    Router::get('/', 'App\Controller\WebSocketController');
});

4.创建对应控制器

<?php

namespace App\Controller;


use Hyperf\Contract\OnCloseInterface;
use Swoole\Http\Response;
use Swoole\WebSocket\Frame;
use Swoole\Server;
use Swoole\WebSocket\Server as WebSocketServer;

class WebSocketController implements \Hyperf\Contract\OnMessageInterface, \Hyperf\Contract\OnOpenInterface,OnCloseInterface
{



    /**
     * @inheritDoc
     */
    public function onMessage($server, Frame $frame): void
    {
        var_dump($frame->data);
        $data = [
            "hello!",
            "hello,叼毛",
            "叼您的啦",
            "做点事,叼毛",
            "中午了,要吃饭了",
            "好烦啊",
            "上班上班",
            "寄",
            "该喝水了,记得喝水,叼毛",
            "还要上班,淦",
            "中午吃啥",
        ];
        $rand = rand(0,10);
        $server->push($frame->fd, '王天佑: ' . $data[$rand]);
    }


    public function onClose($server, int $fd, int $reactorId): void
    {
        echo $fd . '断开连接,处理线程是 ' . $reactorId . PHP_EOL;
    }

    public function onOpen($server, $request): void
    {
        $server->push($request->fd, $request->fd . ' 号客户端已连接!' . PHP_EOL);
    }

}

5.启动

在这里插入图片描述

6.来个连接测试一下

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>websocket</title>
</head>
<body>
<div>
    <textarea name="content" id="content" cols="30" rows="10"></textarea>
    <button onclick="send();">发送</button>
</div>
<ul id="messageList"></ul>

<script>
    let ws = new WebSocket('ws://192.168.210.144:9502')
    ws.onopen = event => {
        console.log('连接服务器成功');
    }

    ws.onmessage = event => {
        let data = event.data;
        let ul = document.getElementById('messageList');
        let li = document.createElement('li');
        li.innerHTML = data;
        ul.appendChild(li);
    }

    ws.onclose = event => {
        console.log('客户端连接关闭');
    }

    function send() {
        let obj = document.getElementById('content');
        let content = obj.value;

        let ul = document.getElementById('messageList');
        let li = document.createElement('li');
        li.innerHTML = "我:"+content;
        ul.appendChild(li);

        ws.send(content);
        obj.value = '';
    }
</script>
</body>
</html>

7.效果

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值