search
HomePHP FrameworkThinkPHPThink-Swoole Tutorial - WebSocket Introduction, Events and Data Sending

Think-Swoole Tutorial - WebSocket Introduction, Events and Data Sending

What is WebSocket

The WebSocket protocol is a new network protocol based on TCP that enables data exchange between the client and the server Becomes simpler and allows the server to actively push data to the client. In the WebSocket API, the browser and the server only need to complete a handshake, and a persistent connection can be created directly between the two for bidirectional data transmission.

Why WebSocket is needed

Because HTTP communication can only be initiated by the client.

What are the characteristics of WebSocket

  • Built on the TCP protocol

  • has small performance overhead , communication is efficient

  • The client can communicate with any server

  • Protocol identification: ws, wss

  • Persistent network communication protocol

WebSocket usage scenarios

Social chat, barrage, multi-player games, collaborative editing, stocks Real-time fund quotations, live sports updates, video conferencing chats, location-based applications, online education and other application scenarios that require high real-time performance.

Before WebSocket, the traditional way we wanted to make a chat program was to use a JavaScript timer to send an HTTP request to the server every second to check whether there are new messages.

With WebSocket, the client sends a WebSocket connection request to the server in HTTP mode through the browser, and then the server sends a response. This process is usually called a "handshake". The browser and the server only need to perform a handshake action, and then a fast channel is formed between the browser and the server to upgrade the protocol to WebSocket. If there is new message, the server will actively push the message to the client.

What is SocketIO?

WebSocket is the latest specification proposed by HTML5. Although mainstream browsers already support it, there may still be incompatibilities. In order to be compatible with all The browser provides programmers with a consistent programming experience. SocketIO encapsulates WebSocket, AJAX and other communication methods into a unified communication interface. That is to say, when we use SocketIO, we don’t have to worry about compatibility issues, the bottom layer will be automatically selected. The best way to communicate. Therefore, WebSocket is a subset of SocketIO, and Think-Swoole parses the data sent to the server according to SocketIO.

Enable WebSocket service in ThinkPHP 6

1. Set "websocket. enable" in the configuration file config/swoole.php to true.

2. Create listening events, create WsConnect, WsClose, and WsTest (this can be named arbitrarily and must correspond to the client). Enter the following commands in the project root directory:

php think make:listener WsConnect
php think make:listener WsClose
php think make:listener WsTest

app/ The listening class file just created will be generated in the listener directory, and business logic can be written in the corresponding event class. Let’s print the $event variable here first. The $event in the Connect event is the app\Request request object, and the $event in the Test custom message receiving event is the message sent by the client.

3. Define the event listening class in the array listen key in app/event.php:

app/event.php
'listen'    => [
        'AppInit'  => [],
        'HttpRun'  => [],
        'HttpEnd'  => [],
        'LogLevel' => [],
        'LogWrite' => [],
        //监听连接,swoole 事件必须以 swoole 开头
        'swoole.websocket.Connect' => [
            app\listener\WsConnect::class
        ],
        //监听关闭
        'swoole.websocket.Close' => [
            \app\listener\WsClose::class
        ],
        //监听 Test 场景
        'swoole.websocket.Test' => [
            \app\listener\WsTest::class
        ],
    ],

swoole.websocket.Connect: The client establishes a connection with the server and completes the handshake event, that is onOpen event in Swoole. Record here the connection ID (fd) between your own program user and the client, etc. Not required, recommended definition.

swoole.websocket.Close: Client connection closing event, optional.

swoole.websocket.Test: Customized Test event; used to receive test event messages sent by the client. Multiple Test events can be defined in a project, such as chat, positioning, and customer service function events, which can correspond to Test1, Test2, Test3, etc.

WebSocket events can also be configured in the "websocket. listen" of the config/swoole.php configuration file:

'listen' => [
    // 首字母大小写都可以;值应该是字符串非数组
    'connect' => 'app\listener\WsConnect',
    'close'   => 'app\listener\WsClose',
    'test'    => 'app\listener\WsTest'
],

4. Start the service in the project root directory: php think swoole start. The bottom layer will automatically determine whether the current request is HTTP or WebSocket.

Establishing a connection between the client and the server

Now we make an HTML page and establish a connection to our server through HTML5 WebSocket. Create a new test.html anywhere with the following content:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

消息:<input type="text" id="message">
接收者:<input type="text" id="to">
<button onclick="send()">发送</button>
<script>
    var ws = new WebSocket("ws://127.0.0.1:9501/");
    ws.onopen = function(){
        console.log(&#39;连接成功&#39;);
    }
    ws.onmessage = function(data){
        console.log(data);
    }
    ws.onclose = function(){
        console.log(&#39;连接断开&#39;);
    }
    function send()
{
        var message = document.getElementById(&#39;message&#39;).value;
        var to = document.getElementById(&#39;to&#39;).value;
        console.log("准备给" + to + "发送数据:" + message);
        ws.send(JSON.stringify([&#39;test&#39;,{
            //这里可以自己定义属性
            to:to,
            message:message
        }])); //发送的数据必须是 "[&#39;test&#39;,数据]" 这种格式
    }
</script>
</body>
</html>

HTML5 WebSocket For an introduction, you can visit here to learn.

In the front-end code, var ws = new WebSocket("ws://127.0.0.1:9501/"); My server is local, and the port number configured in the swoole.php configuration file is 9501, so Visit 127.0.0.1:9501, ws is the WebSocket protocol, and like HTTP and HTTPS, it has WS and WSS protocols. ws.onmessage can accept messages.

Next, access this HTML page through the browser and open the browser debugging console. You can see the words successful connection and the parameters printed by the server:

Think-Swoole Tutorial - WebSocket Introduction, Events and Data Sending

Then we send a message in the input box of the HTML page we just created, and our information is printed in the console:

Think-Swoole Tutorial - WebSocket Introduction, Events and Data Sending

The Swoole listening service terminal also received the message we sent:

Think-Swoole Tutorial - WebSocket Introduction, Events and Data Sending

This is because we are in app/listener /WsTest prints the $event variable.

Finally, let me explain the code ws.send(JSON.stringify(['test',{to:to,message:message}])); in the front-end page. The function of JSON.stringify() is Convert the JavaScript object into a JSON string. The to and message attributes are customized by us. Test is the Test event defined by the backend. This name must correspond to the backend. Since think-swoole parses the sent data according to SocketIO, the data you send should be in the string form of "['event name', the actual data to be sent]": the first parameter test is the corresponding server The Test event on the end is used to distinguish real-time communication logic business in more scenarios; the second parameter is the data you actually send, which can be a string, data, or object. It is obtained by the $event parameter on the server side.

The above is the detailed content of Think-Swoole Tutorial - WebSocket Introduction, Events and Data Sending. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:阿dai哥. If there is any infringement, please contact admin@php.cn delete
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),