Message sending

In the previous section we learned how to create a ws module and connect to the server through the client.

You can see from the sample code that there is a simple message to send.

 ... 
/** @var \Swoole\WebSocket\Server $server */
$server->push($fd, 'hello, welcome! :)');
... 
  • The server here is the swoole \Swoole\WebSocket\Server object.
  • $fd is the connection ID with the client, which indicates a different client

Use \server()

In addition to using $server to send messages, we can also use the swowt packaged \server() or \Swoft::server() to send messages.

E.g:

 \server()->sendTo($fd, 'hi, 你好啊!');
\Swoft::server()->sendTo($fd, 'hi, 你好啊!'); 

Description:

  • Is an instance object of Swoft\WebSocket\Server\WebSocketServer
  • Various methods APIs for sending messages have been encapsulated internally.
  • When the foreground is running, sending a message through it can see the message sending log from the console.

Messaging API

Note that the following methods are all in the class: Swoft\WebSocket\Server\WebSocketServer

Sent to a client

 public function sendTo(int $receiver, string $data, int $sender = 0): int 

Parameter Description:

  • $receiver int receiver fd
  • $data string message data to be sent
  • $sender int sender's fd. Optional

Example:

 \server()->sendTo($fd, 'hi, 你好啊!'); 

Sent to some specified clients

 public function sendToSome(string $data, array $receivers = [], array $excluded = [], int $sender = 0, int $pageSize = 50): int 

Parameter Description:

  • $data string message data to be sent
  • $receivers int[] specifies the list of recipient fd
  • $excluded int[] Excluded recipient fd list
  • $sender int sender's fd. Optional

Method description:

  • When $receivers has data, $excluded will be ignored. At this point, the message is specified to be sent to these recipients.
  • When $receivers is empty
    • If $excluded has a value, it will send a message other than these people.
    • If $excluded is empty, it is equivalent to sending a message to everyone.

Example:

 \server()->sendToSome('hi, 你们好啊!', [$fd0, $fd1, ...]); 

Broadcast message

Send a message to everyone except sender . Send using pagination, every 50 pages, until all are sent

 broadcast(string $data, array $receivers = [], array $excluded = [], int $sender = 0): int 

Send to all clients

 public function sendToAll(string $data, int $sender = 0, int $pageSize = 50): int 

Sending a message to all clients is equivalent to a full broadcast. Send using pagination, every 50 pages, until all are sent

Parameter Description:

  • $data string message data to be sent
  • $sender int sender's fd. Optional

Example:

 \server()->sendToAll('hi, 大家好啊!'); 

Send

The parameters sendToSome same as sendToSome

It will automatically call one of the above methods ( sendTo , sendToAll , sendToSome ) according to the parameter judgment.

/docs/2.x/en/websocket-server/message-send.html
progress-bar