Home > PHP Framework > ThinkPHP > How to use WebSocket for real-time communication in ThinkPHP6?

How to use WebSocket for real-time communication in ThinkPHP6?

WBOY
Release: 2023-06-12 10:40:39
Original
2084 people have browsed it

WebSocket is a full-duplex communication protocol that can establish a real-time connection between the server and the client to achieve real-time communication. In Web development, the commonly used PHP framework is ThinkPHP. So how to use WebSocket for real-time communication in ThinkPHP6?

  1. Install the swoole extension

First you need to install the swoole extension on the server. You can use the composer command to install it:

composer require swoole/swoole
Copy after login

Note: Using the swoole extension is required PHP version>=7.0.

  1. Create WebSocket service

In ThinkPHP6, you can create a WebSocket service through custom commands. Open the command line tool, enter the project root directory, and execute the following command:

php think make:command WebSocket
Copy after login

After executing the command, the WebSocket.php file will be generated in the app/command directory. In this file, add the following code:

<?php
namespace appcommand;

use swoole_websocket_server;
use swoole_http_request;
use thinkconsoleCommand;
use thinkconsoleInput;
use thinkconsoleOutput;

class WebSocket extends Command
{
    protected function configure()
    {
        // 给命令起一个名字
        $this->setName('swoole:websocket')
            ->setDescription('Start websocket server');
    }

    protected function execute(Input $input, Output $output)
    {
        $server = new swoole_websocket_server("0.0.0.0", 9501);

        // 监听WebSocket连接打开事件
        $server->on('open', function (swoole_websocket_server $server, swoole_http_request $request) {
            echo "connection open: {$request->fd}
";
        });

        // 监听WebSocket消息事件
        $server->on('message', function (swoole_websocket_server $server, $frame) {
            echo "received message: {$frame->data}
";

            // 广播消息给所有连接的客户端
            $server->push($frame->fd, "this is server");
        });

        // 监听WebSocket连接关闭事件
        $server->on('close', function ($ser, $fd) {
            echo "connection close: {$fd}
";
        });

        $server->start();
    }
}
Copy after login

Execute the following command to start the WebSocket service:

php think swoole:websocket
Copy after login
  1. Use WebSocket in the view

In the view, you can use JavaScript's WebSocket API to communicate with the server in real time. For example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>
    <script>
        var ws = new WebSocket('ws://localhost:9501');

        ws.onopen = function(){
            console.log('WebSocket open');
        };

        ws.onmessage = function(ev){
            console.log('WebSocket message: ' + ev.data);
        };

        ws.onclose = function(){
            console.log('WebSocket close');
        };
    </script>
</body>
</html>
Copy after login

The above code creates a WebSocket instance and connects to the local WebSocket service. When the server sends a message, the onmessage function is called for processing. You can send messages to the server by calling the send function of the instance.

At this point, the WebSocket service has been successfully created and established a real-time communication connection with the front end.

Summary

In ThinkPHP6, with the help of swoole extension, the WebSocket real-time communication function can be easily realized. By enabling the WebSocket service through custom commands, and combining it with the JavaScript WebSocket API, real-time communication can be achieved in web applications to meet a variety of business needs.

The above is the detailed content of How to use WebSocket for real-time communication in ThinkPHP6?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template