Swoft2 WebSocket启动和测试

swoft 的 github项目地址:https://github.com/swoft-cloud/swoft

建立新WS项目 (Create new project)

使用swoft-cli工具为Websocket创建新项目。

php swoftcli.phar create:app --type ws swoft-ws-app

cd swoft-ws-app

composer install

启动服务器 (Start server)

php bin/swoft ws:start命令启动Websocket服务器,如下所示:

$ php bin/swoft ws:start


Information Panel

*******************************************************************************************

* WebSocket | Listen: 0.0.0.0:18308, type: TCP, mode: Process, worker: 8

*******************************************************************************************

模块 (Module)

使用swoft-cli工具创建新的websocket模块。

php swoftcli.phar gen:ws-mod echo --prefix /echo

回声模块( app/WebSocket/EchoModule.php )的代码如下:

<?php declare(strict_types=1);

namespace App\WebSocket;

use Swoft\Http\Message\Request;
use Swoft\Http\Message\Response;
use Swoft\WebSocket\Server\Annotation\Mapping\WsModule;
use Swoft\WebSocket\Server\Annotation\Mapping\OnOpen;
use Swoft\WebSocket\Server\Annotation\Mapping\OnHandshake;
use Swoole\WebSocket\Server;

/**
 * Class EchoModule - This is an module for handle websocket
 *
 * @WsModule("/echo")
 */
class EchoModule {
    /**
     * @OnHandshake()
     * @param Request $request
     * @param Response $response
     * @return array
     */
    public function checkHandshake(Request $request, Response $response): array {
        
        // some validate logic ...
        return [TRUE, $response];
        
    }
    
    /**
     * @OnOpen()
     * @param Server $server
     * @param Request $request
     * @param int $fd
     * @return mixed
     */
    public function onOpen(Server $server, Request $request, int $fd) {
        $server->push($fd, 'hello, welcome! :)');
    }
}

测试 (Test)

在这里使用swoft-devtool连接WebSocket服务器。

swoft-devtool组件中使用php bin/swoft dclient:ws /echo命令连接WebSocket服务器,可以看到如下所示的连接成功消息。

Begin connecting to websocket server: 127.0.0.1:18308 path: /echo

Success connect to websocket server. Now, you can send message

INTERACTIVE

================================================================================

server> ?Opened, welcome #1!

client> hi

server> Recv: hi

client>

DevTool访问出错不可用的,请使用下面的页面做测试。

WebSocket 聊天室测试页面前端代码


在这里插入图片描述
地址是对的,那为什么链接不了呢?
原因是,你没有开启ws服务。

# cd swoft/bin
# php swoft ws:start

会发现,还是链接不了。咋回事呢?
http对应的是:ws
https对应的是: wss

好嘛,那你提示的例如,就不能说清楚点?
在这里插入图片描述

然后,你就可以发送消息内容了。
对了,开启ws服务默认是开启http服务的,所以你web的也可以正常访问。

猜你喜欢

转载自blog.csdn.net/JineD/article/details/112463213