websocket+php+js实现服务度端向前端推送消息
来源:原创
时间:2020-09-09
作者:脚本小站
分类:PHP
先要为php安装 swoole.so 模块:
wget https://github.com/swoole/swoole-src/archive/v1.9.1-stable.tar.gztar -xf v1.9.1-stable.tar.gz cd swoole-src-1.9.1-stable/ phpize ./configure --with-php-config=/usr/bin/php-config make make install ll /usr/lib64/php/modules/ php -m | grep swoole vim /etc/php.ini extension=swoole.so
示例文档:
https://wiki.swoole.com/wiki/page/479.html
js:
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> </head> <body> <button onclick="send()">send message</button> <script> var wsServer = 'ws://10.3.149.85:9502'; var websocket = new WebSocket(wsServer); websocket.onopen = function (evt) { console.log("Connected to WebSocket server."); }; websocket.onclose = function (evt) { console.log("Disconnected"); }; // 当有消息从后端发过来就会自动执行此函数 websocket.onmessage = function (evt) { console.log(evt); console.log('Retrieved data from server: ' + evt.data); }; websocket.onerror = function (evt, e) { console.log('Error occured: ' + evt.data); }; function send(){ websocket.send("send message"); } </script> </body> </html>
php:
<?php //创建websocket服务器对象,监听0.0.0.0:9502端口 $ws = new swoole_websocket_server("0.0.0.0", 9502); //监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) { var_dump($request->fd, $request->get, $request->server); $ws->push($request->fd, "hello, welcome\n"); }); //监听WebSocket消息事件,接收到客户端发来的消息怎么处理 $ws->on('message', function ($ws, $frame) { echo "Message: {$frame->data}\n"; $ws->push($frame->fd, "server: {$frame->data}"); }); //监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd) { echo "client-{$fd} is closed\n"; }); $ws->start();