WebSocket Usage (nodejs)

WebSocket is introduced

  • WebSocket is a protocol for full duplex communication over a single TCP connection provided by HTML5. Allows the server to actively push data to the client (HTTP protocol has a flaw: communication can only be initiated by the client).
  • In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.
  • Ajax polling: The browser needs to make continuous requests to the server, but HTTP requests may contain long headers, where only a small portion of the data is actually valid, which obviously wastes a lot of bandwidth and other resources. Polling is inefficient and wasteful (because you have to keep connecting, or HTTP connections are always open).

WebSocket characteristics

  • The server can actively push information to the client, and the client can also actively send information to the server
  • Based on TCP protocol, the implementation of the server side is relatively easy.
  • It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the handshake phase uses HTTP protocol, so it is not easy to mask the handshake and can pass various HTTP proxy servers.
  • The data format is relatively light, with low performance overhead and high communication efficiency.
  • You can send text or binary data.
  • There are no same-origin restrictions, and clients can communicate with any server.
  • The protocol identifier isws(If encrypted, otherwisewss), the server URL is the URL.

WebSocket event

The following are the events related to WebSocket objects. Suppose we create a Socket object (var Socket = new WebSocket(url, [protocol]);) using the above code. :

The event Event handler describe
open Socket.onopen Triggered when the connection is established
message Socket.onmessage Triggered when the client receives data from the server
error Socket.onerror Triggered when a communication error occurs
close Socket.onclose Triggered when the connection is closed

WebSocket method

The following are methods for WebSocket objects. Suppose we created the Socket object using the code above:

methods describe
Socket.send() Use the connection to send data
Socket.close() Close the connection

WebSocket simple example

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>WenSocket</title>
    <style>
        div{
            width: 200px;
            height: 200px;
            border:1px solid;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <input type="text" placeholder="Please enter the content">
    <button>submit</button>
    <div></div>
    
    <script>
        const input = document.querySelector('input')
        const button = document.querySelector('button')
        const div = document.querySelector('div')
        
        // Create a WebSocket instance
        const socket = new WebSocket("ws://echo.websocket.org")
        
        // Listen to whether the service is connected
        socket.addEventListener('open'.() = >{
            div.innerHTML = "Service link successful"
        })
        // Button triggers a click event that sends the contents of the input box to the Websocket
        Chrome F12 open console "Network" WS "echo.websocket.org" messages
        button.addEventListener('click'.() = >{
            const value = input.value
            socket.send(value)
        })
        // Insert the received data into the div
        socket.addEventListener('message'.(e) = >{
            console.log(e)
            div.innerHTML = e.data
        })
    </script>
</body>
</html>
Copy the code

Use Node to build websocket service

  • Installation module: YARN add nodejs-websocket

  • Configure the service (www.npmjs.com/package/nod… Socket = new WebSocket(“ws://echo.websocket.org”) const socket = new WebSocket(“ws://localhost:3000”)

    var ws = require("nodejs-websocket")
    
    // Create a service server. Each time the user links, the function is executed and a connect object is created for the current user
    var server = ws.createServer(connect= > {
        // Whenever data is received from the user, the text event is emitted and the data is passed in
        connect.on("text".data= > {
            // Give the user response data
            // connect.sendText(data.toUpperCase()+"!!!" ) // Convert case and concatenate strings
            connect.send(data)
        })
    
        // Listen for webSocket to disconnect
        connect.on("close".() = > {
            console.log("Websocket connection down....")})// Listen for webSocket exceptions
        connect.on("error".() = > {
            console.log("Abnormal websocket connection....")
        })
    })
    server.listen(3000.() = > {
        console.log("websocket running")})Copy the code

WebSocket chat room

Chat room basic function builds

index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>WenSocket</title>
    <style>
    </style>
</head>
<body>
    <input type="text" placeholder="Please enter the content">
    <button>submit</button>
    <div></div>
    <script>
        
        const input = document.querySelector('input')
        const button = document.querySelector('button')
        const div = document.querySelector('div')
        const socket = new WebSocket('ws://localhost:3000')

        socket.addEventListener('open'.() = >{
            div.innerText = "Welcome to the chat room"
        })
        button.addEventListener('click'.() = >{
            const value = input.value
            socket.send(value)
            input.value = ' '
        })
        
        socket.addEventListener('message'.(e) = >{
            //div. InnerText = e.data // This method overwrites the original data
            const dv = document.createElement('div')
            dv.innerText = e.data
            div.appendChild(dv)
        })
    </script>
</body>
</html>
Copy the code

Optimization – Add color to different types of information

app.js

const ws =require('nodejs-websocket')

// Count the number of users. Whenever a user accesses the function, it is executed and a Conncet object is created for the user
var count = 0

/* Main changes to the code ----- **/
/* type: message type, 0: message to join the chat room, 1: message to leave the chat room, 2: normal message **/
const TYPE_ENTER = 0
const TYPE_LEAVE = 1
const TYPE_MSG = 2
/* ------ main change code **/

const server = ws.createServer(connect= >{
    count++
    connect.userName = ` user${count}`
    
    /* Main changes to the code ----- **/
    broadcast({
        type: TYPE_ENTER,
        msg: `${connect.userName}Came in `.time: new Date().toLocaleTimeString()
    })
    /* ------ main change code **/

    connect.on('text'.data= >{
        // connect.send(data) send sends data only to the current user
        /* Main changes to the code ----- **/
        broadcast({
            type: TYPE_MSG,
            msg: data,
            time: new Date().toLocaleTimeString()
        })
    })
    /* ------ main change code **/

    connect.on('close'.() = >{
        /* Main changes to the code ----- **/
        broadcast({
            type: TYPE_LEAVE,
            msg: ` user${count}Left `.time: new Date().toLocaleTimeString()
        })
        /* ------ main change code **/
        count--
        console.log('Connection closed... ')
    })

    connect.on("error".() = >{
        console.log('Abnormal connection... ')})})//An Array with all connected clients. It's useful for broadcasting a message
function broadcast(msg) {
    server.connections.forEach((connect) = > {
        connect.send(JSON.stringify(msg))
    })
}

server.listen(3000.() = >{
    console.log('websocket running..... ')})Copy the code

index.html

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>WenSocket</title>
    <style>
    </style>
</head>

<body>
    <input type="text" placeholder="Please enter the content">
    <button>submit</button>
    <div></div>
    <script>

        const input = document.querySelector('input')
        const button = document.querySelector('button')
        const div = document.querySelector('div')
        const socket = new WebSocket('ws://localhost:3000')
        
        /* Main changes to the code ----- **/
        const TYPE_ENTER = 0
        const TYPE_LEAVE = 1
        const TYPE_MSG = 2
        /* ------ main change code **/

        socket.addEventListener('open'.() = > {
            div.innerText = "Welcome to the chat room"
        })
        button.addEventListener('click'.() = > {
            const value = input.value
            socket.send(value)
            input.value = ' '
        })
        socket.addEventListener('message'.(e) = > {
            // div.innerText = e.data
            /* Main changes to the code ----- **/
            const data = JSON.parse(e.data)
            /* ------ main change code **/
           // console.log(data)
            const dv = document.createElement('div')
            /* Main changes to the code ----- **/
            dv.innerText = data.msg+"-- -- -- -- --"+data.time
            if(data.type===TYPE_ENTER){
                dv.style.color = '#28dab4'
            }
            else if(data.type===TYPE_LEAVE){
                dv.style.color = '#ff0707'
            }else if(data.type===TYPE_MSG){
                dv.style.color = '# 000000'
            }
            /* ------ main change code **/
            div.appendChild(dv)
        })
    </script>
</body>

</html>
Copy the code