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!