Home > Article > Backend Development > The principle and detailed explanation of PHP's real-time push of system messages to the client
In our actual development process, some data need to be obtained in real time;
For example, order information in the ERP system, process approval in the OA system, etc. need to be processed in a timely manner , then we can no longer use the http protocol; of course, we can also use the polling mechanism.
But most of the polling requests are useless, wasting bandwidth and server resources.
At this time we have to use the websocket protocol to meet this business need;
Preparation work:
Installation PHP-swoole
Expand;
Post the code directly;
<?php new class { private $_serv = null; public function __construct() { $this->_serv = new swoole_websocket_server('0.0.0.0', 6552); $this->_serv->set(array( 'worker_num' => 2, 'dispatch_mode' => 3, 'log_file' => 'swoole.log', )); //增加个监听端口 $udpworker = $this->_serv->listen("127.0.0.1", 6553, SWOOLE_SOCK_UDP); $udpworker->on('Packet', function ($serv, $data, $addr) { $data = json_decode($data, true); if(!empty($data)){ //你的业务逻辑 } }); $this->_serv->on('open', array($this, 'onStart')); $this->_serv->on('message', array($this, 'onMessage')); $this->_serv->on('close', array($this, 'onClose')); $this->_serv->start(); } public function onStart($serv, $request) { echo "server: connect success with fd {$request->fd}\n"; } //format:'{"school_class_id":"1","school_id":"2"}' public function onMessage($serv, $frame) { /**start*你的业务逻辑***/ } public function onClose($serv, $fd) { echo "client {$fd} closed\n"; } } ?>
Principle:
Create first The websocket server object listens to the 0.0.0.0:6552 port, and then uses the service object to listen to the UDP 6553 port. Client messages are sent to interface 6553 and then sent to the user via port 6552.
For more related php knowledge, please visit php tutorial!
The above is the detailed content of The principle and detailed explanation of PHP's real-time push of system messages to the client. For more information, please follow other related articles on the PHP Chinese website!