WebSocket is introduced

The following is from Wikipedia:

WebSocket is a network transport protocol that enables full-duplex communication over a single TCP connection and is located at the application layer of the OSI model. The WebSocket protocol was standardized by THE IETF in 2011 into RFC 6455 and later supplemented by RFC 7936. The WebSocket API in Web IDL is standardized by W3C.

WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to 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 between the two.

history

WebSocket was originally referred to as TCPConnection in the HTML5 specification as a placeholder for tcp-based socket apis.

The name WebSocket was later coined by Ian Hickson and Michael Carter in the # WhatWG IRC chat room and subsequently written by Ian Hickson and included in the HTML5 specification, Announced on Michael Carter’s Cometdaily blog.

In June 2008, Michael Carter conducted a series of discussions that resulted in a protocol called WebSocket.

WebSocket was first supported in Chrome 4 in December 2019 and enabled by default

The WebSocket protocol was moved to ETFs by the W3C and WHATWG in February 2010 and revised twice under the direction of Ian Hickson.

In December 2011, WebSocket became an international protocol.

background

Before WebSocket, many sites used polling (requesting the latest data from the server every once in a while) for all of their push techniques. The downside of this pattern is obvious: you need to keep sending requests, which can be very resource-intensive.

A newer technology is Comet, which allows for two-way communication but also requires frequent and costly requests.

So along came the man, and WebSocket only needed the browser to establish a connection with the server, two-way real-time communication.

The advantages of the WebSocket

  • Real time. Personally, this is the biggest advantage, because this feature makes WebSocket very useful in many application scenarios. Such as games, real-time online chat, real-time warning and so on.
  • Less control overhead. Since you only need to establish a connection once, the server and browser costs are low. And WebSocket protocol packet header data is relatively small, server to browser only 2-10 bytes; The browser to the server only needs to add another 4 bytes as the mask.
  • The connection status remains. A stateful connection is established between the browser and the server. All subsequent communications can be omitted except for the first connection, which carries some state data.
  • Scalability is supported. Users can extend subprotocols based on WebSocket
  • Better compression. Compared to HTTP compression, Websocket, with appropriate extension support, can use the context of the previous content, which can significantly improve compression when passing similar data.
  • Good compatibility with HTTP protocol. Ports 80 and 443 are used by default, and HTTP is used in the handshake phase. Therefore, it is not easy to mask and can pass through this HTTP proxy server
  • Better binary support
  • There is no homology restriction, so Mom doesn’t have to worry about my cross-domain problems anymore

support

As you can see, WebSocket is supported by all modern browsers (including IE’s predecessor, Edge, not to mention all modern browsers), and mobile support is pretty good, so why not?

The native WebSocket

This article will not discuss native WebSocket (which is also very simple) because libraries such as socket.io are used in real projects. If you want to learn native WebSocket, you can look at WebSocket in MDN.

www.ruanyifeng.com/blog/2017/0…

Excellent WebSocket library

If you search WebSocket on GitHub, you can see that there are 17K results for repositories and 17509 for JavaScript:

  • Ws: back-end WebSocket communication library for nodeJS
  • SocketJS: Multiple WebSocket libraries available, including JavaScript (server and client), Erlang, Python/Tornado, Java/vert.x
  • Socket. IO: similar to SocketJS, but more extensive: JavaScript (server and client), Java, C++, Swift, DartPython,.net. Which one do I choose? IO, because vue-socket. IO)
  • Total.js: NodeJs library for the server

How is it used in Vue projects

For vUE projects, vuE-socket. IO is not too convenient to use. You can create a link at a time and use it freely during application events.

How is it used in Vue projects

Small example

I made a small example of an anonymous online chat system based on Vuetify and vue-socket. IO, where you can click on a portal to experience the joy of WebSocket.

WebSocket can really do whatever it wants 😋

The installation

CDN: cdn.jsdelivr.net/npm/vue-soc…

Or through the package manager:

yarn add vue-socket.io
npm i vue-socket.io
Copy the code

The global

Add the following code to main.ts:

Use (new VueSocketIO({debug: true, // enable socket console output connection: 'http://39.105.103.136:9521/', / / links / / configuration vuex vuex: {store, actionPrefix: MutationPrefix: 'socket' // socket trigger prefix}}))Copy the code

The configuration is as follows:

* * * * parameter * * * * type ** Default value ** ** Specifies whether to select ** Description * * * *
debug Boolean `false` optional Enable console output
connection String/Socket.io-client `null` Will choose WebSocket service address or socket. IO instance
vuex.store Vuex `null` optional Vuex instance
vuex.actionPrefix String `null`

optional

The message sent by the server is the vuEX action prefix in the following format:

<ACTION_PREFIX><EVENT_NAME>

vuex.mutationPrefix String `null`

optional

When a server sends a message, it corresponds to the mutaiton prefix of vuex in the following format:

<ACTION_PREFIX><EVENT_NAME>

Use in components

An instance of the $socket.emit() method that can be used in the component has the following format:

Vue.$socket.emit(eventName: string,eventData:any)
Copy the code

Such as:

this.$socket.emit('Login', {
  username: this.username
})
Copy the code

Subscribe and unsubscribe

The subscribed and unsubscribed methods on the Sockets property are declared as follows:

interface Vue {
  $socket: SocketIOClient.Socket,
    sockets: {
      subscribe(eventName: string, handler: socketHandler<Vue>): void,
      unsubscribe(eventName: string): void,
    }
}
Copy the code

So the same goes for subscriptions and contact subscriptions:

this.sockets.subscribe('EVENT_NAME', (data) => {
    this.msg = data.message
})

this.sockets.unsubscribe('EVENT_NAME')
Copy the code

Combined with vuex

If store is injected into the main.ts file, vue-socket. IO will trigger the corresponding mutation and action on receiving the corresponding message in the format of < configured prefix >< message name > :

export default class Chat extends VuexModule { onlineUsers: Users = {} record: Array<Record> = [] @mutation // Server message name Users, socket is the prefix of the load submitted by the SOket, data is the data sent by the server socketUsers (data: Users) {this.onlineUsers = data} @mutation // Server message name is Record, socket is the prefix of the soket load, data is the data sent by the server. Array<Record>) { this.record = data } }Copy the code

Although mutation and action can be set, the best way to update state is by setting the action

A complete example

The full example can be seen here

Server example

Since it is not the back end, only a simple back-end example is made to work with the front end project, see here for details