zoukankan      html  css  js  c++  java
  • HTML5+NodeJs实现WebSocket即时通讯

     声明:本文为原创文章,如需转载,请注明来源WAxes,谢谢!

      最近都在学习HTML5,做canvas游戏之类的,发现HTML5中除了 canvas这个强大的工具外,还有WebSocket也很值得注意。可以用来做双屏互动游戏,何为双屏互动游戏?就是通过移动端设备来控制PC端网页游 戏。这样的话就要用到实时通讯了,而WebSocket无疑是最合适的。WebSocket相较于HTTP来说,有很多的优点,主要表现在 WebSocket只建立一个TCP连接,可以主动推送数据到客户端,而且还有更轻量级的协议头,减少数据传送量。所以WebSocket暂时来说是实时 通讯的最佳协议了。

      至于服务器语言选择nodeJs,一是因为自己是做前端的,对javascript比较熟悉,相比于其他后台语言,自然会更喜欢nodeJs了,二是NodeJs本身事件驱动的方式很擅长与大量客户端保持高并发的连接。所以就选择NodeJs了。

      服务器的实现很简单,先装一个nodeJs的模块,叫nodejs- websocket , 直接在nodeJs命令行中敲入:npm install nodejs-websocket回车就可以安装好了,然后就可以开始建立服务器了,因为有了nodejs-websocket模块,所以很多工作都不用 我们自己做,直接调用别人封装好的方法就行了:

      【服务端代码】,根据客户端传来的消息判断哪个是game1,哪个是game2,保存connection对象。

    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;
            }
    
            if(game1Ready&&game2Ready){
                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代码】:通过点击获取三个框的内容,传到服务器

    <!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{ 200px;height:200px;border:1px solid;text-align: center;line-height: 200px;display: inline-block;}
        </style>
    </head>
    <body>
        <div id="mess">正在连接...</div>
        <div class="kuang">
            <div class="value" id="value1">小明小明</div>
            <div class="value" id="value2">大胸大胸</div>
            <div class="value" id="value3">小张小张</div>
        </div>
    
        <script>
            var mess = document.getElementById("mess");
            if(window.WebSocket){
                var ws = new WebSocket('ws://192.168.17.80: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){
                    mess.innerHTML = "连接成功"
                    document.querySelector(".kuang").onclick = function(e){
                        var time = new Date();
                        ws.send(time + "  game1点击了“" + e.target.innerHTML+"”");
                    }
                }
            }
        </script>
    </body>
    </html>
    

      【game2代码】:获取服务推送来的消息,并且显示

    <!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}
        </style>
    </head>
    <body>
        <div id="mess"></div>
    
        <script>
            var mess = document.getElementById("mess");
            if(window.WebSocket){
                var ws = new WebSocket('ws://192.168.17.80: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){
                    var time = new Date();
                    mess.innerHTML+=time+"的消息:"+e.data+"<br>"
                }
            }
        </script>
    </body>
    </html>
    

      代码非常简单:很容易看懂,nodejs-WebSocket的调用也非常简洁明了,具体nodejs-websocket的API可以看https://www.npmjs.org/package/nodejs-websocket,里面都有介绍,自己测试一下,就很容易了,客户端的实现也是很简单,就通过onopen,onmessage等几个方法就可以实现了。

  • 相关阅读:
    [转]对Lucene PhraseQuery的slop的理解
    Best jQuery Plugins of 2010
    15 jQuery Plugins To Create A User Friendly Tooltip
    Lucene:基于Java的全文检索引擎简介
    9 Powerful jQuery File Upload Plugins
    Coding Best Practices Using DateTime in the .NET Framework
    Best Image Croppers ready to use for web developers
    28 jQuery Zoom Plugins Creating Stunning Image Effect
    VS2005 + VSS2005 实现团队开发、源代码管理、版本控制(转)
    禁止状态栏显示超链
  • 原文地址:https://www.cnblogs.com/xupeiyu/p/4234263.html
Copyright © 2011-2022 走看看