Table of Contents
Environment requirements
Create project
Create controller
Register routing
Writing WebSocket communication logic
Configure WebSocket service
Run the WebSocket service
Summary
Home PHP Framework ThinkPHP Implementing Websocket broadcast using ThinkPHP6

Implementing Websocket broadcast using ThinkPHP6

Jun 20, 2023 am 08:41 AM
thinkphp websocket broadcast

With the continuous development of modern web applications, real-time communication has become one of the necessary functions. WebSocket technology is one of the most popular real-time communication methods, which can establish a persistent two-way connection between the server and the client to achieve real-time communication.

ThinkPHP is a very popular PHP framework. ThinkPHP 6 comes with the Swoole extension package, making it very simple to use WebSocket technology. This article will introduce how to use the ThinkPHP 6 framework to implement a WebSocket broadcast function.

Environment requirements

Before you start, you need to prepare the following environment:

  • PHP 7.2
  • Swoole extension
  • Composer
  • Basic Web development knowledge

Create project

First, we need to create a new project:

composer create-project topthink/think my-project
Copy after login

Then, for the convenience of using WebSocket , we need to add the Swoole extension in the composer.json file of the project:

"require": {
    "topthink/think-swoole": "^2.0",
    "swoole/swoole": "^4.7"
}
Copy after login

After completion, run the following command to install:

composer install
Copy after login

Create controller

Next, we need to create a controller to handle WebSocket requests. Create a file named Websocket.php in the app/controller directory and write the following code:

<?php

declare(strict_types=1);

namespace appcontroller;

use thinkswooleWebsocket as SwooleWebsocket;
use SwooleWebSocketFrame;

class Websocket extends SwooleWebsocket
{
    /**
     * 监听连接事件
     * @param SwooleWebSocketServer $server
     * @param SwooleHttpRequest $request
     */
    public function onOpen($server, $request)
    {
    }

    /**
     * 监听接收消息事件
     * @param SwooleWebSocketServer $server
     * @param Frame $frame
     */
    public function onMessage($server, Frame $frame)
    {
    }

    /**
     * 监听关闭事件
     * @param SwooleWebSocketServer $server
     * @param int $fd
     */
    public function onClose($server, $fd)
    {
    }
}
Copy after login

In the above code, we inheritedthinkswooleWebsocket class and override three of its methods:

  • onOpen method is used to listen for connection events;
  • The onMessage method is used to listen to receive message events; the
  • onClose method is used to listen to close events.

Currently, these methods do not do anything. Next, we will add the logic of WebSocket communication to these methods.

Register routing

After the controller is created, we need to register it in the routing. Add the following content in the app/route.php file:

use thinkacadeRoute;

Route::post('/ws', 'Websocket@onMessage')->middleware(    hinkmiddlewareAllowCrossDomain::class);
Copy after login

The Route::post method is used here to register the route. The request method of this route is POST, the path is /ws, and the request is mapped to the onMessage method of the Websocket controller.

Writing WebSocket communication logic

Now, we have completed the creation and registration of WebSocket routes and controllers. Next, we need to add the logic for WebSocket communication in the controller. We will use Swoole's WebSocket server to implement WebSocket communication.

In the onOpen method, we can obtain the client's connection object and store it for subsequent use. In the onMessage method, we can get the message sent by the client and broadcast this message to other clients. In the onClose method, we need to remove the client from the connection pool.

Create a file named WebSocketServer.php in the app/controller directory and write the following code:

<?php

declare(strict_types=1);

namespace appcontroller;

use SwooleHttpResponse;
use SwooleWebSocketFrame;
use SwooleWebSocketServer;
use thinkswoolewebsocketHandlerInterface;

class WebSocketServer implements HandlerInterface
{
    /**
     * @var array $connections
     */
    private $connections = [];

    /**
     * 监听连接事件
     * @param Server $server
     * @param SwooleHttpRequest $request
     */
    public function onOpen(Server $server, SwooleHttpRequest $request): void
    {
        $this->connections[$request->fd] = $request->fd;

        echo "client-{$request->fd} is connected
";
    }

    /**
     * 监听消息事件
     * @param Server $server
     * @param Frame $frame
     */
    public function onMessage(Server $server, Frame $frame): void
    {
        foreach ($this->connections as $fd) {
            $info = $server->getClientInfo((int)$fd);
            if ($info && isset($info['websocket_status']) && $info['websocket_status'] == WEBSOCKET_STATUS_FRAME) {
                $server->push($fd, $frame->data);
            } else {
                unset($this->connections[$fd]);
            }
        }

        echo "received message from client-{$frame->fd}: {$frame->data}
";
    }

    /**
     * 监听关闭事件
     * @param Server $server
     * @param int $fd
     * @param int $reactorId
     */
    public function onClose(Server $server, int $fd, int $reactorId): void
    {
        unset($this->connections[$fd]);

        echo "client-{$fd} is closed
";
    }

    /**
     * @param Response $response
     */
    public function onHandShake(Request $request, Response $response): bool
    {
        // Do nothing
        return true;
    }
}
Copy after login

Configure WebSocket service

Before writing the WebSocket service code, we need to create a configuration file named swoole.php in the config directory and write the following content:

return [
    'socket_type' => 'websocket',
    'host'        => '0.0.0.0',
    'port'        => 9501,
    'mode'        => SWOOLE_PROCESS,
    'sock_type'   => SWOOLE_SOCK_TCP,
    'settings' => [
        'worker_num' => swoole_cpu_num(),
    ],
    'handler' => ppcontrollerWebSocketServer::class,
];
Copy after login

In the above code, we tell the application how to start the Swoole WebSocket service through the configuration file. We start the websocket socket type, bind it on 0.0.0.0:9501, and enable multi-process mode, using the TCP protocol. worker_num The configuration item sets the number of processes of the server. swoole_cpu_num() is used here to return the number of system CPUs; handler The configuration item specifies what we have mentioned above. Created WebSocketServer class.

Run the WebSocket service

After completing the code to create and configure the WebSocket service, we need to run the code to start the WebSocket service. Just execute the following command on the command line:

php think swoole start --mode=websocket
Copy after login

The Websocket service has been started and you can test it by accessing your application. You can use this address: ws://your-domain:9501/ws. Open multiple tabs in the browser to test the WebSocket connection, message sending and receiving functions respectively.

Summary

This article introduces how to use the ThinkPHP 6 framework to implement a WebSocket broadcast function. We accomplish this by creating controllers, registering routes and writing WebSocket communication logic, and configuring the WebSocket service. This example can be used as a simple WebSocket best practice and provides a reference for us to develop more advanced WebSocket functions.

The above is the detailed content of Implementing Websocket broadcast using ThinkPHP6. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

How to achieve real-time communication using PHP and WebSocket How to achieve real-time communication using PHP and WebSocket Dec 17, 2023 pm 10:24 PM

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages ​​in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

PHP and WebSocket: Best practices for real-time data transfer PHP and WebSocket: Best practices for real-time data transfer Dec 18, 2023 pm 02:10 PM

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

How does Java Websocket implement online whiteboard function? How does Java Websocket implement online whiteboard function? Dec 17, 2023 pm 10:58 PM

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

SSE and WebSocket SSE and WebSocket Apr 17, 2024 pm 02:18 PM

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration

How to use Java and WebSocket to implement real-time stock quotation push How to use Java and WebSocket to implement real-time stock quotation push Dec 17, 2023 pm 09:15 PM

How to use Java and WebSocket to implement real-time stock quotation push Introduction: With the rapid development of the Internet, real-time stock quotation push has become one of the focuses of investors. The traditional stock market push method has problems such as high delay and slow refresh speed. For investors, the inability to obtain the latest stock market information in a timely manner may lead to errors in investment decisions. Real-time stock quotation push based on Java and WebSocket can effectively solve this problem, allowing investors to obtain the latest stock price information as soon as possible.

See all articles