一、node

var ws = require("nodejs-websocket");
console.log("开始建立连接...")

var server = ws.createServer(function(conn){
    conn.on("text", function (str) {
        console.log("收到的信息为:"+str)/*
        conn.sendText(str)*/

        //回调
        var backStr = 'get the str'
        conn.send(JSON.stringify(backStr))
        console.log('发送回调信息')
        
    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    });
}).listen(8001)
console.log("WebSocket建立完毕")

二、html

<!DOCTYPE html>
<html>
<head>
    <title>massage</title>
</head>
<body>
    <div>
        <input id="msg" type="text" name="">
    </div>
    <button id="sendMessage">发送消息给服务器</button>
    <div>
        <span>来自server:</span>
        <span id="serverMsg"></span>
    </div>
    <script type="text/javascript">
        window.onload = function () {
            var sendBtn = document.getElementById('sendMessage')
            sendBtn.addEventListener('click', function () {
                var msg = document.getElementById('msg')
                sendMessageToServer(msg.value);
            })

            function sendMessageToServer (msg) {
                msgJSON = JSON.stringify(msg)
                var socket = new WebSocket("ws://localhost:8001")
                console.log(socket)
                setTimeout( function () {
                    if (socket.readyState == WebSocket.OPEN) {
                        socket.send(msgJSON)
                    }else {
                        console.log("the socket is not open")
                    }
                    //接收server返回内容
                    socket.onmessage = function (event) {
                        console.log(event)
                        var backMsg = JSON.parse(event.data)
                        if (backMsg) {
                            document.getElementById('serverMsg').innerHTML = backMsg
                            console.log(backMsg)
                        }
                    }
                }, 500)
            }
        }
    </script>
</body>
</html>