
我们将要学习的这篇文章是:如何安装和运行swoft websocket服务器。
本文是Swoft WebSocket服务器上一系列文章之一。 让我们了解Swoft!
斯沃夫特是什么?
Swoft是一个PHP高性能微服务协程框架。 它已经发布了很多年,并已成为php的最佳选择。
它可以像Go,内置的协程Web服务器和通用协程客户端一样,并且驻留在内存中,独立于传统的PHP-FPM。
有类似的Go语言操作,类似于Spring Cloud框架的灵活注释。
通过三年的积累和方向探索,Swoft使Swoft成为了PHP世界中的Spring Cloud,它是PHP高性能框架和微服务管理的最佳选择。
Github
建立新专案
使用swoft-cli
工具为Websocket创建新项目。
php swoftcli.phar create:app --type ws swoft-ws-app cd swoft-ws-app composer install
启动服务器
用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 *******************************************************************************************
Websocket服务器的端口是18308
模组
使用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 { public function checkHandshake(Request $request, Response $response): array {
测验
这里使用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>
Github