WebSocket 协议是基于 TCP 的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信,允许服务器主动发送信息给客户端。
下面的代码演示了利用 Swoole 实现服务器向浏览器主动推送数据的例子。
Server端代码:
<?php $server = new Swoole\Websocket\Server('192.168.1.1', 9501); $server->on('Open', function($server, $req) { echo 'connection open: '.$req->fd . "\n"; $server->push($req->fd, "welcome to www.sunbloger.com"); for ($i=1; $i<=9; $i++) { $server->push($req->fd, $i); sleep(3); } }); $server->on('Message', function($server, $req) { echo "client(".$req->fd."): " . $req->data . "\n"; }); $server->on('Close', function($server, $fd) { echo "connection close: {$fd}\n"; }); $server->on('WorkerStart', function ($server, $workerId) { echo "worker started: {$workerId}\n"; }); $server->start(); ?>
浏览器端(Client)代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WebSocket Client</title> </head> <body> <input type="text" id="text"> <input type="submit" value="发送数据" onclick="send()"> <div id="msg"></div> </body> <script> var isSupport; if (typeof WebSocket != 'undefined') { isSupport = true; } else { isSupport = false; } if (isSupport == true) { var msg = document.getElementById("msg"); var wsServer = 'ws://192.168.1.1:9501'; var websocket = new WebSocket(wsServer); websocket.onopen = function (e) { console.log("websocket server open."); }; websocket.onmessage = function (e) { msg.innerHTML += e.data +'<br>'; } websocket.onclose = function (e) { console.log("websocket server close."); }; } function send() { if (isSupport == true) { var text = document.getElementById('text').value; document.getElementById('text').value = ''; //向服务器发送数据 websocket.send(text); } else { alert("浏览器不支持WebSocket!"); } } </script> </html>
阳光部落原创,更多内容请访问http://www.sunbloger.com/