C/C++教程

Swoole WebSocket服务器测试

本文主要是介绍Swoole WebSocket服务器测试,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.新建服务端ws.php

<?php
//创建WebSocket Server对象,监听0.0.0.0:9502端口
$ws = new Swoole\WebSocket\Server('0.0.0.0', 8892);

//监听WebSocket连接打开事件
$ws->on('Open', function ($ws, $request) {
    $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();

2.新建test.htm客户端测试

备注:ws://和wss://前缀分别表示WebSocket连接和安全的WebSocket连接。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Swoole-Web-Socker测试</title>
</head>
<body>
    <script>
        var wsServer = 'ws://124.220.192.59:8892';
        var websocket = new WebSocket(wsServer);
        websocket.onopen = function (evt) {
            console.log("Connected to WebSocket server.");
        };

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

        websocket.onmessage = function (evt) {
            console.log('Retrieved data from server: ' + evt.data);
        };

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

    </script>

</body>
</html>

 

这篇关于Swoole WebSocket服务器测试的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!