使用浏览器,PHP 来构建的应用,发现都是每次浏览器发送一次http 请求,PHP 回一个响应。javascript
这样,后端的PHP 在处理屡次http请求是,每次都是不一样的进程在处理。 这就加大了开销, 并且,PHP 在处理屡次的http请求时,先后多个PHP进程之间的感受都没啥联系,php
这些先后PHP进程之间怎么才能共享一些资源呢?好比,和第三方的tcp链接, 数据库链接, modbus tcp 的链接 能保持长链接, 先后多个PHP进程均可以共享,这样就不用每次html
的PHP进程都要去从新创建tcp链接(太浪费资源了),java
基于这些思考? 那有什么好的办法呢????web
------------------------------------------------------数据库
哈哈,这样浏览器websocket client 和服务端端PHP的websocket server 就能够通讯上了, 测试成功!!nice后端
下面是具体的代码和方法步骤!浏览器
------------------------------------------------服务器
客户端(浏览器), websocket 代码:websocket
<html> <head> <meta charset="UTF-8"> <title>Web sockets test</title> <script type="text/javascript"> var ws; function ToggleConnectionClicked() { try { ws = new WebSocket("ws://47.88.215.46:9501");//链接服务器 ws.onopen = function(event){alert("已经与服务器创建了链接\r\n当前链接状态:"+this.readyState);}; ws.onmessage = function(event){alert("接收到服务器发送的数据:\r\n"+event.data);}; ws.onclose = function(event){alert("已经与服务器断开链接\r\n当前链接状态:"+this.readyState);}; ws.onerror = function(event){alert("WebSocket异常!");}; } catch (ex) { alert(ex.message); } }; function SendData() { try{ var content = document.getElementById("content").value; if(content){ ws.send(content); } }catch(ex){ alert(ex.message); } }; function seestate(){ alert(ws.readyState); } </script> </head> <body> <button id='ToggleConnection' type="button" onclick='ToggleConnectionClicked();'>链接服务器</button><br /><br /> <textarea id="content" ></textarea> <button id='ToggleConnection' type="button" onclick='SendData();'>发送个人名字:beston</button><br /><br /> <button id='ToggleConnection' type="button" onclick='seestate();'>查看状态</button><br /><br /> </body> </html>
客户端效果:
服务端PHP建立的websocket server 代码(使用了 swoole开源库):
<?php //建立websocket服务器对象,监听0.0.0.0:9502端口 $ws = new swoole_websocket_server("127.0.0.1", 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();
把websocket server 跑起来: