Using WebSocket to achieve simple Chat room effect in Vue

Let’s take a look at Websockets before we use them

WebSocket

If Ajax is like SMS, sending and getting information, Websocket is like making a phone call. The goal of WebSocket is to allow users to get real-time updates without having to refresh the browser.

Using Ajax polling can put a lot of strain on the server and consume a lot of server bandwidth and resources. Faced with this situation, HTML5 defines the WebSocket protocol, which can better save server resources and bandwidth and realize real-time push in the real sense.

WebSocket protocol was born in 2008 and became an international standard in 2011. All browsers already support it.

Features:

  • The server can take the initiative to push information to the client, and the client can also take the initiative to send information to the server, which is a real two-way equal dialogue and belongs to a server push technology. This is also its biggest characteristic.
  • 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 heavy, with low performance overhead and high communication efficiency.
  • You can send text or binary data.
  • Clients can communicate with any server without the same origin restriction.
  • The protocol identifier is WS (or WSS if encrypted), and the server URL is the URL.

WebSocket event

  1. Socket.onopen Triggered when the connection is established
  2. Socket. onMessage Triggered when the client receives data from the server
  3. Socket. onError Triggered when a communication error occurs
  4. Socket.onclose Triggered when the connection is closed

WebSocket method

  1. Socket.sebd() uses the connection to send data
  2. Socket.close() closes the connection

Nodejs + WebSocket example

Install the WebSocket

npm i nodejs-websocket -S
Copy the code

Create a new index.js server

var ws = require("nodejs-websocket");
console.log("Start establishing connections...")
var server = ws.createServer(function(conn){
 conn.on("text".function (str) {
 console.log("message:"+str)
 conn.sendText("My name is Web Xiu!");
 })
 conn.on("close".function (code, reason) {
 console.log("Close connection")}); conn.on("error".function (code, reason) {
 console.log("Abnormal shutdown")}); }).listen(8001)
console.log("WebSocket setup completed")
Copy the code

The client

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <button> link </button> </body> </ HTML > <script> let BTN = document.querySelector('button'); btn.onclick = function(){ if (window.WebSocket) { var ws = new WebSocket('ws://localhost:8001'); Ws. onopen = function (e) {console.log(" connect to server successfully "); Ws. send(" What's your name? ); } ws.onclose = function (e) {console.log(" server down "); } ws.onerror = function () {console.log(" connection error "); Ws. onmessage = function (e) {let message = "message:" + e.data + ""; console.log(message); } } } </script>Copy the code

Article reference:

www.toutiao.com/i6683747519… (# Nodejs + WebSocket brief introduction and Examples – Chapter 1)

www.ruanyifeng.com/blog/2017/0… (# WebSocket tutorial)