Node.js笔记-使用nodejs-websocket构建WebSocket服务

x33g5p2x  于2021-11-10 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(286)

首先安装nodejs-websocket

npm install nodejs-websocket

构造如下程序:

wsServer.js

var ws = require("nodejs-websocket")

var PORT = 3000

var server = ws.createServer(function (conn) {

    console.log("New connection")
    conn.on("text", function (str) {

        console.log("Received "+str)
        conn.sendText(str.toUpperCase()+"!!!")
    })
    conn.on("close", function (code, reason) {

        console.log("Connection closed")
    })

    conn.on("error", function(err){

        console.log("handle err");
        console.log(err);
    })

}).listen(PORT)

前端代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>
    <h1>Echo Test</h1>
    <input id="sendTxt" type="text" />
    <button id="sendBtn">发送</button>
    <div id="recv"></div>
    <script type="text/javascript">
        let websocket = new WebSocket("ws://127.0.0.1:3000");
        websocket.onopen = function () {

            console.log('websocket open');
            document.getElementById("recv").innerText = "Connected";
        }

        websocket.onclose = function () {

            console.log('websocket close');
        }

        websocket.onmessage = function (ev) {

            console.log(ev.data);
            document.getElementById("recv").innerHTML = ev.data;
        }

        document.getElementById("sendBtn").onclick = function () {

            let txt = document.getElementById("sendTxt").value;
            console.log(txt);
            websocket.send(txt);
        }

    </script>
</body>
</html>

运行截图:

相关文章