«

使用html+swoole通过websocket实现一个简单的聊天室代码

时间:2024-2-18 10:05     作者:韩俊     分类: Javascript


使用html+swoole通过websocket实现一个简单的聊天室代码。

客户端代码:

<html>
<head>客户端</head>
<body>
<script type="text/javascript">
    var sock = null;
    var wsuri = "ws://127.0.0.1:1234";
    window.onload = function () {
        console.log("onload");
        sock = new WebSocket(wsuri);
        sock.onopen = function () {
            console.log("connected to " + wsuri);
        }
        sock.onclose = function (e) {
            console.log("connection closed (" + e.code + ")");
        }
        sock.onmessage = function (e) {
            console.log("message received: " + e.data);
        }
    };

    function send() {
        var msg = document.getElementById('message').value;
        sock.send(msg);
    };
</script>
<h1>WebSocket Echo Test</h1>
<form>
    <p>
        Message: <input id="message" type="text" value="Hello, world!">
    </p>
</form>
<button onclick="send();">Send Message</button>
</body>
</html>

服务端代码:

<?php

$serv = new swoole_websocket_server("127.0.0.1", 9502);

$serv->on('Open', function ($server, $req) {
    echo "connection open: " . $req->fd;
});

$serv->on('Message', function ($server, $frame) {
    echo "message: " . $frame->data;
    $server->push($frame->fd, json_encode(["hello", "world"]));
});

$serv->on('Close', function ($server, $fd) {
    echo "connection close: " . $fd;
});

$serv->start();

标签: javascript

热门推荐