Nodejs-WebSocket to achieve front-end interaction

WebSocket

Speaking of network protocols, I have to say HTTP, but the HTTP protocol has an obvious flaw: communication can only be initiated by the client.
Server data sending changes cannot actively inform the client, but the client needs to continuously poll to check whether the server data has changed.
Not to mention low efficiency, but also a waste of resources.

In this context, it is HTML5defined that WebSocket协议it can be performed on a single TCP connectionZensokou Tsushin , Can better save server resources and bandwidth, and can communicate in more real-time.

Websocket uses ws or wss 统一资源标志符(URI). Which wssrepresents used TLS的Websocket.

ws://example.com/wsapi
wss://secure.example.com/wsapi

WebsocketWith HTTPand HTTPSusing the same TCP端口, can bypass most firewalls restrictions. By default, Websocketprotocol 80端口; run TLStime on, use the default 443端口.

Herein is used in the server NodeJs
may be present at a stamp download

Simultaneous configuration cnpm(npm Taobao mirror)

npm install -g cnpm --registry=https://registry.npm.taobao.org

verification:

cnpm -v

Project

Examples of this article directory:

node_modules
client.html
server.js

Currently only text interaction is realized.

Library package

The server side uses the nodejs-websocket library (can be stamped)

installation:

cnpm install nodejs-websocket

Insert picture description here
These results appear in the catalog is automatically generated node_modulesfolder

  • node_modules

Server

var ws = require("nodejs-websocket");
console.log("Connecting ...");

var server = ws.createServer(function(conn){
    
    

    conn.on("text",function(str){
    
    
        //服务端打印接收到的数据
        console.log("News:" + str);
        //接收到的数据打上标记“Server-”,再发送回客户端
        conn.sendText("Server-"+str);
    });

    conn.on("close",function(code,reason) {
    
    
        console.log("Disconnected.");
    });

    conn.on("error",function(code,reason) {
    
    
        console.log("Error.")
    });
}).listen(8848);

console.log("Server runing!");
  • server.js

Client

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Game1 Test Demo</title>
</head>

<body>

    <div id="mess">正在连接...</div>
    <div>
        <button id="state1" >第一重</button>
        <button id="state2">第二重</button>
        <button id="state3">第三重</button><br><br>
        <a> 已发送:</a>
        <a id="sendnews"></a><br>
        <a>已接收:</a>
        <a id="receivenews"></a>
    </div>

    <script>
        var mess = document.getElementById("mess");
        if(window.WebSocket){
     
     
            //这里修改为本机IP地址
            var ws = new WebSocket('ws://10.0.2.15:8848');

            ws.onopen = function(e){
     
     
                console.log("连接服务器成功");
                mess.innerHTML = "连接成功"
                ws.send("TestClient");
            }

            ws.onclose = function(e){
     
     
                console.log("服务器关闭");
                mess.innerHTML = "服务器关闭"
            }

            ws.onerror = function(){
     
     
                console.log("连接出错");
                mess.innerHTML = "连接出错"
            }

            //收到服务器数据后的回调函数
            ws.onmessage = function(e){
     
     
                document.getElementById("receivenews").innerHTML=e.data;
            }

            //设置点击事件
            document.getElementById("state1").onclick = function(e){
     
     
                ws.send("昨夜西风凋碧树,独上西楼,望尽天涯路。");
                document.getElementById("sendnews").innerHTML="昨夜西风凋碧树,独上西楼,望尽天涯路。"
            }
            document.getElementById("state2").onclick = function(e){
     
     
                ws.send("衣带渐宽终不悔,为伊消得人憔悴。");
                document.getElementById("sendnews").innerHTML="衣带渐宽终不悔,为伊消得人憔悴。"
            }
            document.getElementById("state3").onclick = function(e){
     
     
                ws.send("众里寻他千百度,蓦然回首,那人却在灯火阑珊处。");
                document.getElementById("sendnews").innerHTML="众里寻他千百度,蓦然回首,那人却在灯火阑珊处。"
            }
        }
    </script>
</body>

</html>
  • client.html

test

Turn on the server first

node server.js

Open again client.html

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_40774605/article/details/106626706
Recommended