NodeJs simple WebSocket WebSocket instant messaging NodeJs simple instant messaging

NodeJs simple WebSocket instant messaging

 

 

As for the server language selection nodeJs, first, because she was in the front, on the javascript more familiar with the background compared to other languages, you will naturally prefer the nodeJs,

Second NodeJs own event-driven way is very good at keeping high concurrent connection with the large number of clients. So I chose the NodeJs.


 

Server implementation is very simple, first install a module nodeJs, called nodejs-websocket, knock directly on nodeJs command line: npm install nodejs-websocket Enter on it installed,

Then we can begin to build the server, because nodejs-websocket module, so do not have a lot of work to do ourselves, others packaged directly call methods on the line:


 

Server code

According to the news client to decide which is game1, which is game2, save the connection object.

Copy the code
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) { 
        the console.log ( "close connection") 
    }); 
    conn.on ( "error", function (code, reason) { 
        the console.log ( "abnormal shutdown" ) 
    }); 
.}) the listen (8001) 
the console.log ( "establishing a WebSocket complete")
Copy the code

[Game1 Code]: Get the contents of three boxes by clicking to the server

Copy the code
<!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 class="kuang">
        <div class="value" id="value1">小明小明</div>
        <div class="value" id="value2">大胸大胸</div>
        <div class="value" id="value3">小张小张</div>
    </div>

    <script>
        Mess document.getElementById = var ( "Mess"); 
        IF (window.WebSocket) { 
            var a WebSocket new new WS = ( 'WS: //192.168.17.80: 8001'); 

            ws.onopen = function (E) { 
                the console.log ( "connect server successfully"); 
                ws.send ( "Game1"); 
            } 
            ws.onclose = function (E) { 
                the console.log ( "server closed"); 
            } 
            ws.onerror = function () { 
                the console.log ( "connection error"); 
            } 

            ws.onmessage function = (E) { 
                mess.innerHTML = "connection successful" 
                document.querySelector () function the onclick = (E) { "Kuang.". 
                    var = new new Time a Date (); 
                    ws.send (Time + "Game1 clicked" "+ e.target.innerHTML +" "" );
                }
            }
        }
    </script>
</body>
</html>
Copy the code

[Code] game2: obtaining service push message sent, and the display

Copy the code
<!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"); 
                the console.log ( "Server off");
            }
            ws.onclose = function(e){ 
            } 
            ws.onerror = function () { 
                console.log ( "Connection error"); 
            } 

            ws.onmessage = function (E) { 
                var new new Time = a Date (); 
                mess.innerHTML + = time + "message:" + + e.data "<br>" 
            } 
        } 
    </ Script> 
</ body> 
</ HTML>
Copy the code

Run shot:


 
The code is very simple: it is easy to understand, call nodejs-WebSocket is also very clear and concise, specific nodejs-websocket the API can be seen https://www.npmjs.org/package/nodejs-websocket ,
Which has introduced its own test, it is easy to achieve the client is very simple, just a few methods onopen, onmessage, etc. can be achieved.

 

Source: https: //www.cnblogs.com/axes/p/3586132.html

 

As for the server language selection nodeJs, first, because she was in the front, on the javascript more familiar with the background compared to other languages, you will naturally prefer the nodeJs,

Second NodeJs own event-driven way is very good at keeping high concurrent connection with the large number of clients. So I chose the NodeJs.


 

服务器的实现很简单,先装一个nodeJs的模块,叫nodejs-websocket , 直接在nodeJs命令行中敲入:npm install nodejs-websocket回车就可以安装好了,

然后就可以开始建立服务器了,因为有了nodejs-websocket模块,所以很多工作都不用我们自己做,直接调用别人封装好的方法就行了:


 

服务端代码

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

Copy the code
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建立完毕")
Copy the code

【game1代码】:通过点击获取三个框的内容,传到服务器

Copy the code
<!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 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>
Copy the code

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

Copy the code
<!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 ( "Server closed"); 
            } 
            ws.onerror = function () { 
                console.log ( "Connection error"); 
            } 

            ws.onmessage = function (E) { 
                var new new Time = a Date (); 
                mess.innerHTML + = time + "message:" + + e.data "<br>" 
            } 
        } 
    </ Script> 
</ body> 
</ HTML>
Copy the code

Run shot:


 
The code is very simple: it is easy to understand, call nodejs-WebSocket is also very clear and concise, specific nodejs-websocket the API can be seen https://www.npmjs.org/package/nodejs-websocket ,
Which has introduced its own test, it is easy to achieve the client is very simple, just a few methods onopen, onmessage, etc. can be achieved.

 

Source: https: //www.cnblogs.com/axes/p/3586132.html

Guess you like

Origin www.cnblogs.com/shaozhu520/p/11327886.html