Как стать автором

PHP Microservice Framework Swoft: WebSocket Server Part 1

PHP *Программирование *Yii *Laravel *

This article we are going to learn is: How to install and run the swoft websocket server.

This article is one of a series of articles on the Swoft WebSocket Server. Let's learn about Swoft!

What is Swoft?

Swoft is a PHP high performance microservice coroutine framework. It has been published for many years and has become the best choice for php.

It can be like Go, built-in coroutine web server and common coroutine client and is resident in memory, independent of traditional PHP-FPM.

There are similar Go language operations, similar to the Spring Cloud framework flexible annotations.

Through three years of accumulation and direction exploration, Swoft has made Swoft the Spring Cloud in the PHP world, which is the best choice for PHP's high-performance framework and microservices management.


Create new project

Use swoft-cli tool to create new project for Websocket.

php swoftcli.phar create:app --type ws swoft-ws-app
cd swoft-ws-app
composer install

Start server

Start Websocket server with php bin/swoft ws:start command, you can see below:

$ php bin/swoft ws:start

                                      Information Panel
  * WebSocket | Listen:, type: TCP, mode: Process, worker: 8

Port of Websocket sever is 18308


Use swoft-cli tool to create new websocket module.

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

Code for echo module(app/WebSocket/EchoModule.php) like this:

<?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! :)');


Here use swoft-devtool to connect WebSocket server.

Use php bin/swoft dclient:ws /echo command in swoft-devtool component to connect WebSocket server, you can see connection success message like below.

Begin connecting to websocket server: path: /echo
Success connect to websocket server. Now, you can send message
server> ?Opened, welcome #1!
client> hi
server> Recv: hi


Всего голосов 14: ↑10 и ↓4 +6
Просмотры 860
Комментарии Комментировать