PHP Framework
ThinkPHP
Think-Swoole's WebSocket messages, broadcasts and Swoole native method callsThink-Swoole's WebSocket messages, broadcasts and Swoole native method calls
Think-Swoole Tutorial WebSocket Messages, Broadcasts and Swoole Native Method Calls
What is the fd of the client
fd is the unique identifier of the client in Swoole , fd is reused. When the connection is closed, fd will be reused by the newly entered connection. The TCP connection fd being maintained will not be reused.
Get the fd of the current client
app/listener/WsConnect.php
<?php
declare (strict_types = 1);
namespace app\listener;
use \think\swoole\Websocket;
class WsTest
{
/**
* 事件监听处理
*
* @return mixed
*/
public function handle($event,Websocket $ws)
{
// $ws = app('think\swoole\Websocket'); // 单例
//获取当前发送消息客户端的 fd
var_dump($ws -> getSender());
}
}test.html
<!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('连接成功');
}
ws.onmessage = function(data){
console.log(data.data);
}
ws.onclose = function(){
console.log('连接断开');
}
function send()
{
var message = document.getElementById('message').value;
var to = document.getElementById('to').value;
console.log("准备给" + to + "发送数据:" + message);
ws.send(JSON.stringify(['test',{
to:to,
message:message
}])); //发送的数据必须是 ['test',数据] 这种格式
}
</script>
</body>
</html>Open the browser Multiple tags to simulate multiple client connections, all access the test.html file, the console will print out the fd of each client, as shown below we open three tags for access:
In other words, the messages sent by the server will be received by ws.onmessage in HTML.
Send a message to the client of the specified fd (single or group)
app/listener/WsTest.php
<?php
declare (strict_types = 1);
namespace app\listener;
use \think\swoole\Websocket;
class WsTest
{
/**
* 事件监听处理
*
* @return mixed
*/
public function handle($event,Websocket $ws)
{
// $ws = app('think\swoole\Websocket'); // 单例
//获取当前发送消息客户端的 fd
var_dump($ws -> getSender());
//发送给指定 fd 的客户端,包括发送者自己
$ws -> to(intval($event['to'])) -> emit('testcallback',$event['message']);
}
}$ws -> to() is the setting Recipient fd or chat room name. If sending to multiple people, you can set multiple arrays, such as [1,2,3], fd must be an integer. $ws -> emit() is a message sending method. The first parameter is the event name, which is used in multiple scenarios and can be defined arbitrarily, just like the Test in the previous article where the client sends a message to the server. The second parameter is the content to be sent, which can be a string or an array. If called separately without setting the recipient, the message will be sent to the current fd.
Restart the Think-Swoole service and open three clients to connect. The fd is 1, 2, and 3. Now, now, we use the client with fd 1 to send a message to the client with fd 2. Client:

After sending, it can be seen that only the clients with fd 1 and 2 can receive the message (that is to say, the message sender himself will also receive the message), However, the client with fd 3 did not receive the message:

After sending, it can be seen that only the clients with fd 1 and 2 can receive the message (that is to say, the message The sender itself will also receive the message), but the client with fd 3 did not receive the message:

Sending a broadcast message
The broadcast message is Send a message to all clients except yourself.
app/listener/WsConnect.php
<?php
declare (strict_types = 1);
namespace app\listener;
use \think\swoole\Websocket;
class WsTest
{
/**
* 事件监听处理
*
* @return mixed
*/
public function handle($event,Websocket $ws)
{
//获取当前发送消息客户端的 fd
var_dump($ws -> getSender());
//发送广播消息
$ws -> broadcast() -> emit('testcallback',$event['message']);
}
}$ws -> The broadcast() method is to send broadcast messages.
But if you want to receive broadcast messages yourself, you need to add a $ws -> to($ws -> getSender()) -> emit('testcallback',$event[' message']); That's it.
Simulate a client to send a message to another client
Suppose my current fd is 1, but I want to simulate using a client with fd 2 to send a message to a client with fd 3. Just set the sender fd and the receiver fd:
$ws -> setSender(2) -> to(3) -> emit('testcallback',$event['message']);
After testing, 1 did not receive the message, but 2 and 3 both received it.
Get Swoole\WebSocket\Server
Suppose we now need a function to determine whether a client is a valid client, that is, whether the handshake with the server is successful. The Think-Swoole extension does not have this function, but according to the Swoole official documentation, there is an isEstablished function that can complete the functions we need. So how to get the native Swoole function through Think-Swoole? The answer is to get the Swoole\WebSocket\Server class. There are two ways:
1. app('swoole.server');
2. app('think\swoole\Manager') -> getServer();
After instantiation, you can call Swoole native methods, such as:
$manager = app('think\swoole\Manager'); $manager -> getServer() -> isEstablished(2);
Attachment: \think\Swoole\Websocket class object method:
broadcast settings Send broadcast messages
isBroadcast Determine whether the current broadcast mode is
to Set the recipient fd or chat room name (can be set in an array to multiple )
getTo Get the recipient fd or chat room name
join The current client joins the specified chat room (can be multiple)
leave The current client leaves the specified chat room (can be multiple)
emit message is sent
close Close the current connection
getSender Get the current client id (i.e. fd)
-
setSender Set the sender’s fd
The above is the detailed content of Think-Swoole's WebSocket messages, broadcasts and Swoole native method calls. For more information, please follow other related articles on the PHP Chinese website!
What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PMThe 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?Mar 18, 2025 pm 04:57 PMArticle 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?Mar 18, 2025 pm 04:54 PMThe 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?Mar 18, 2025 pm 04:51 PMThe 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?Mar 18, 2025 pm 04:50 PMThinkPHP'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?Mar 18, 2025 pm 04:49 PMThe 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?Mar 18, 2025 pm 04:46 PMThinkPHP 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?Mar 18, 2025 pm 04:45 PMThe 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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)





