关于NodeJs和Html5实现WebSocket

关于NodeJs和Html5实现WebSocket

1、下载Node.js,安装node-v10.13.0-x64.msi。
https://nodejs.org/en/

2、安装ws模块。
在cmd命令中输入:npm install nodejs-websocket

3、编写一个server.js文件。

var ws = require("nodejs-websocket")
 
//
var server = ws.createServer(function (conn) {
    console.log("New connection");
 
    // 获取连接信息
    conn.on("text", function (str) {
        console.log("Received " + str);
        conn.sendText(str)
    });
 
    // 断开连接的回调
    conn.on("close", function (code, reason) {
        console.log("Connection closed")
    })
 
    // 处理错误事件信息
    conn.on('error', function(err){
        console.log('throw : err');
        console.log(err);
    })
}).listen(8081);
 
console.log('WebSocket server listening on port 8081');

4、启动。
在cmd命令中输入:node server.js

5、websocket.html

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket</title>

    <style>
        html, body {
            font: normal 1em arial, helvetica;
        }

        #log {
            width: 400px;
            height: 200px;
            border: 1px solid #000000;
            overflow: auto;
        }

        #msg {
            width: 330px;
        }
    </style>

    <script>
        var socket;

        function init() {
            var host = "ws://127.0.0.1:8081/";
            try {
                socket = new WebSocket(host);
                socket.onopen = function (msg) {
                    log("Begin Connection!");
                };
                socket.onmessage = function (msg) {
                    log(msg.data);
                };
                socket.onclose = function (msg) {
                    log("Lose Connection!");
                };
            }
            catch (ex) {
                log(ex);
            }
            $("msg").focus();
        }

        function send() {
            var txt, msg;
            txt = $("msg");
            msg = txt.value;
            if (!msg) {
                alert("Message can not be empty");
                return;
            }
            txt.value = "";
            txt.focus();
            try {
                socket.send(msg);
            } catch (ex) {
                log(ex);
            }
        }

        window.onbeforeunload = function () {
            try {
                socket.send('quit');
                socket.close();
                socket = null;
            }
            catch (ex) {
                log(ex);
            }
        };


        function $(id) {
            return document.getElementById(id);
        }
        function log(msg) {
            $("log").innerHTML += "<br>" + msg;
        }
        function onkey(event) {
            if (event.keyCode == 13) {
                send();
            }
        }
    </script>

</head>
<body onload="init()">
<h3>WebSocket</h3>
<br>
<div id="log"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)"/>
<button onclick="send()">发送</button>
</body>
</html>

发表回复

您的电子邮箱地址不会被公开。