PHP微服务框架Swoft:WebSocket服务器第1部分


我们将要学习的这篇文章是:如何安装和运行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 - 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! :)'); } } 

测验


这里使用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


Source: https://habr.com/ru/post/zh-CN471598/


All Articles