This is the 12th day of my participation in Gwen Challenge

concept

  • A durable, full-duplex protocol

persistent

  • HTTP sends a request, receives the response and then disconnects
  • Websocket does not break after communication

Full duplex

  • HTTP can only be sent by the client to the background
  • For Websocket, the server can take the initiative to push information to the client, the client can also take the initiative to send information to the server, the two are two-way

Several states

Are connected

WebSocket database.opening (0) : Connection is being established.Copy the code

Is connected

WebSocket. OPEN (1) : The connection has been established.Copy the code

Is closing

WebSocket. CLOSING (2) : Connection is closing.Copy the code

Has been closed

WebSocket. CLOS (3) : Connection is closing.Copy the code

Commonly used API

See the documentation for more APIS

The constructor

WebSocket(url,[,protocols])
Copy the code
  • Url: indicates the background address
const ws =new WebSocket('ws:localhost:8000')  //
Copy the code

open

  • The connection is successful

close

  • Close the connection

message

  • Received message

error

  • The connection fails
const ws =new WebSocket('ws:localhost:8000')   
ws.addEventListener('open', handleOpen, false)
ws.addEventListener('close', handleClose, false)
ws.addEventListener('error', handleError, false)
ws.addEventListener('message', handleMessage, false) // Data is received
Copy the code

Application scenarios

  • Social chat
  • barrage
  • Co-editing files
  • Some real time applications

Implement a simple chat room

The front end

Receive information

  • The front end receives information by listening for message events

    const ws = new Socket('ws:localhost:8000')  / / ws protocol
    ws.addEventListener('message', handleMessage, false) // Data is received
    function handleMessage(e) {
        console.log(e)
        const msgData = JSON.parse(e.data)
    	console.log(msgData)
    }
    Copy the code

Send a message

  • Websocket provides a send method to send information to the server

    ws.send(JSON.stringify(sendData))// Send a string
    Copy the code

The back-end

  • Here we build a simple backend service with Node, which requires downloading a WS module

    npm install ws
    
    Copy the code

Receive information


const WS = require('ws')
const server = new WS.Server({ port: 8000 }) // The address port must be the same as the previous connection
server.on('connection', handleConnection)  // Register receiving message events while connecting

function handleConnection(ws) {
    console.log('server websocket connection')
    ws.on('message', handleMessage)
}

Copy the code

Send a message

  • The requirement implemented here is that when the background receives a message from one client, it immediately publishes the message to all clients
function handleMessage(msg) {
    // console.log(server.clients)
    // debugger
    server.clients.forEach((c) = > {
        // Iterate over the client
        console.log(c.send)
        c.send(msg) / / send})}Copy the code

rendering