php swoole构建webSocket连接的简单实例

1.客户端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webSocket</title>
</head>
<body>
<p id="status"></p>
<input type="text" id="content" />
<button onclick="clientSend()">发送</button>
<button onclick="clientClose()">关闭连接</button>
<script type="text/javascript">
    var wsServer = "ws://192.168.0.239:9504";
    var webSocket = new WebSocket(wsServer);
    //on方法表示监听服务端动作
    webSocket.onopen = function (event) {
        document.getElementById('status').innerText += "onopen:连接成功\n";
    }
    webSocket.onmessage = function (event) {
        document.getElementById('status').innerText += "onmessage:" + event.data + "\n";
    }
    webSocket.onclose = function (event) {
        document.getElementById('status').innerText += "onclose:连接关闭\n";
    }
    webSocket.onerror = function (event, error) {
        document.getElementById('status').innerText += "onerror:" + error + "\n";
    }
    //客户端发送的操作
    function clientSend() {
        var content = document.getElementById('content').value;
        webSocket.send(content);
        document.getElementById('status').innerText += "send:" + content + "\n";
    }
    function clientClose() {
        webSocket.close();
        document.getElementById('status').innerText += "close:客户端关闭连接\n";
    }
</script>

</body>
</html>

2.服务端:

<?php
    //创建websocket服务器
    $server = new swoole_websocket_server('0.0.0.0', 9504);

    //on
    //open 建立连接 $server 服务器, $request:客户端信息
    $server->on('open', function($server, $request){
        var_dump($request);
        $server->push($request->fd, "welcome \n");
    });
    //message 接收信息
    $server->on('message', function($server, $request){
        echo "message: $request->data";
        $server->push($request->fd, "get it message");
    });
    //close 关闭连接
    $server->on('close', function($server, $request){
        echo "close \n";
    });

    $server->start();

 启动webSocket服务:执行命令:php swoole_websocket.php

 

3.客户端浏览器访问webSocket服务:

(1).浏览器输入输出

(2).服务端输出

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页