美文网首页
WebSocket 服务器

WebSocket 服务器

作者: zhaoxiaohui520 | 来源:发表于2020-07-10 00:12 被阅读0次
一、ws_server.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);
    // var_dump($request->fd);
    // $ws->push($request->fd, "hello, ZHG welcome\n");
    print_r($request->fd);
}); 

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

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

$ws->start();


二、可以使用 Chrome 浏览器进行测试,JS 代码为:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>swoole_webserver测试</h1>

    <script>
        var wsServer = 'ws://sw.dabaicai.ink:9502';
        var websocket = new WebSocket(wsServer);
        websocket.onopen = function (evt) {
            websocket.send("hello xiaohui");
            console.log("Connected -swoole-success");
        };

        websocket.onclose = function (evt) {
            console.log("Disconnected");
        };

        websocket.onmessage = function (evt) {
            console.log('ws-server-return-data: ' + evt.data);
        };

        websocket.onerror = function (evt, e) {
            console.log('Error occured: ' + evt.data);
        };
    </script>

</body>

</html> 

三、测试效果

开启了http服务来测试 WebSocket效果
44.png

相关文章

网友评论

      本文标题:WebSocket 服务器

      本文链接:https://www.haomeiwen.com/subject/rfpycktx.html