浏览器websocket

使用浏览器,PHP 来构建的应用,发现都是每次浏览器发送一次http 请求,PHP 回一个响应。

这样,后端的PHP 在处理多次http请求是,每次都是不同的进程在处理。 这就加大了开销, 而且,PHP 在处理多次的http请求时,前后多个PHP进程之间的感觉都没啥联系,

这些前后PHP进程之间怎么才能共享一些资源呢?比如,和第三方的tcp连接, 数据库连接, modbus tcp 的连接 能保持长连接, 前后多个PHP进程都可以共享,这样就不用每次

的PHP进程都要去重新建立tcp连接(太浪费资源了),

基于这些思考? 那有什么好的办法呢????

------------------------------------------------------

 哈哈,这样浏览器websocket client 和服务端端PHP的websocket server 就可以通信上了, 测试成功!!nice

下面是具体的代码和方法步骤!

------------------------------------------------

客户端(浏览器), 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("已经与服务器建立了连接
当前连接状态:"+this.readyState);};
                ws.onmessage = function(event){alert("接收到服务器发送的数据:
"+event.data);};
                ws.onclose = function(event){alert("已经与服务器断开连接
当前连接状态:"+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
");
});

//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
    echo "Message: {$frame->data}
";
    $ws->push($frame->fd, "server: {$frame->data}");
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed
";
});

$ws->start();

  把websocket server 跑起来:

原文地址:https://www.cnblogs.com/oxspirt/p/6715260.html