html5 nodejs&websocket聊天demo

首先需要安装nodejs

然后安装 npm install nodejs-websocket

以上为nodejs基础知识如有疑问可以查阅相关资料。


首先创建ws.js放到nodejs目录下。


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

var game1 = null,game2 = null , game1Ready = false , game2Ready = false;
var server = ws.createServer(function(conn){
  conn.on("text", function (str) {
    console.log("收到的信息为:"+str)
    if(str==="game1"){
      game1 = conn;
      game1Ready = true;
      //conn.sendText("success");
    }
    if(str==="game2"){
      game2 = conn;
      game2Ready = true;
      //conn.sendText("success");
    }

    if(game1Ready && game2Ready) {
      if(str==="game1" || str==="game2"){
        game1.sendText("success");
        game2.sendText("success");
      }
      else{
        game1.sendText(str);
        game2.sendText(str);
      }

    }

    //conn.sendText(str);
  })
  conn.on("close", function (code, reason) {
    console.log("关闭连接")
  });
  conn.on("error", function (code, reason) {
    console.log("异常关闭")
  });
}).listen(8001)
console.log("WebSocket建立完毕")


然后 创建game1.html和game2.html,为了方便起见也放到nodejs目录下.


game1.html:


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .kuang{text-align: center;margin-top:200px;}
        #mess{text-align: center}
        .value{width: 200px;height:200px;border:1px solid;text-align: center;line-height: 200px;display: inline-block;}
    </style>
</head>
<body>
<div id="mess">正在连接...</div>
<div id="content">

</div>

<div>
    <input type="text" id="mytext"><input type="button" id="dosend" value="发送">
</div>

<script>
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate;
    }

    var mess = document.getElementById("mess");
    var content = document.getElementById("content");
    if(window.WebSocket){
        var ws = new WebSocket('ws://127.0.0.1:8001');

        ws.onopen = function(e){
            console.log("连接服务器成功");
            ws.send("game1");
        }
        ws.onclose = function(e){
            console.log("服务器关闭");
        }
        ws.onerror = function(){
            console.log("连接出错");
        }

        ws.onmessage = function(e){
            if(e.data==="success"){
                mess.innerHTML = "连接成功";
            }
            else{
                content.innerHTML+=getNowFormatDate()+"<br>"+e.data+"<br><br>";
            }
        }
        document.querySelector("#dosend").onclick = function(e){
            ws.send("g1:"+document.querySelector("#mytext").value);
            document.querySelector("#mytext").value = "";
        }
    }
</script>
</body>
</html>


game2.html:


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .kuang{text-align: center;margin-top:200px;}
        #mess{text-align: center}
        .value{width: 200px;height:200px;border:1px solid;text-align: center;line-height: 200px;display: inline-block;}
    </style>
</head>
<body>
<div id="mess">正在连接...</div>
<div id="content">

</div>

<div>
    <input type="text" id="mytext"><input type="button" id="dosend" value="发送">
</div>

<script>
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate;
    }

    var mess = document.getElementById("mess");
    var content = document.getElementById("content");
    if(window.WebSocket){
        var ws = new WebSocket('ws://127.0.0.1:8001');

        ws.onopen = function(e){
            console.log("连接服务器成功");
            ws.send("game2");
        }
        ws.onclose = function(e){
            console.log("服务器关闭");
        }
        ws.onerror = function(){
            console.log("连接出错");
        }

        ws.onmessage = function(e){
            if(e.data==="success"){
                mess.innerHTML = "连接成功";
            }
            else{
                content.innerHTML+=getNowFormatDate()+"<br>"+e.data+"<br><br>";
            }
        }
        document.querySelector("#dosend").onclick = function(e){
            ws.send("g2:"+document.querySelector("#mytext").value);
            document.querySelector("#mytext").value = "";
        }
    }
</script>
</body>
</html>


好的 我们主要的文件都已经创建好了

接下来我们在nodejs目录下运行cmd,键入 node ws.js 回车,会有如下提示:


html5 nodejs&websocket聊天demo


然后我们用chrome分别打开 game1.html和game2.html。最好以两个窗口模式访问,这样更直观。

如图:

html5 nodejs&websocket聊天demo


请注意截图的两个访问地址,不用通过服务器进行访问就可以。

当两个页面都打开以后,两个页面的顶部会同时显示“”“连接成功”。

接下来任意一个窗口发消息后,两个窗口都会同时受到消息。