This is the second day of my participation in the August More text Challenge. For details, see:August is more challenging
background
Websocket: Many websites use polling to implement push technology. Polling is when the browser makes an HTTP request to the server at a specific time interval (such as every second), and the server returns the latest data to the client browser. This traditional model has obvious disadvantages, that is, the browser needs to constantly send requests to the server, but THE HTTP request may contain long headers, in which the actual valid data may be only a small part, obviously this will waste a lot of bandwidth and other resources.
Project requirements:
Before the project is the original webSocket implementation background information push actively, detailed implementation are available at www.runoob.com/html/html5-.
However, the requirement this time is that all connected users need to receive different messages, and only need to receive case messages related to their own departments. The back end requires the front end to send different subscription requests based on different user subscriptions.
Method of use
1, install,
NPM install sockjs – client @ 1.5.1
NPM install [email protected]
Project use version is “sockjs – client” : “^ 1.5.1”, “stompjs” : “^ 2.3.3.” “
2. Introduction module
import SockJS from ‘sockjs-client’;
import Stomp from ‘stompjs’;
3. Business-related code
// Websocket URL http://10.... /.. /webSocket
this.sockjsUrl=
process.env.NODE_ENV === 'development'
? '/api/avc-web/webSocket'
: `${protocol}//${host}/${process.env.VUE_APP_CONTEXT}/webSocket`
async connection() {
const {
data: { deptIndexCode }
} = await getCurUser(); // Obtain the department parameters from the interface
var _this = this;
// Establish the connection object
let socket = new SockJS(this.sockjsUrl);
// Get the client object for the STOMP subprotocol
this.stompClient = Stomp.over(socket);
// Define the authentication information of the client as required
let headers = {
Authorization: ' '
};
// Initiates a WebSocket connection to the server
this.stompClient.connect(
headers,
function(res) {
_this.stompClient.subscribe(`/topic/${deptIndexCode}`.function(msg) {
// _this.arrys.unshift(JSON.parse(msg.body));
console.log(JSON.parse(msg.body));
const newObj = JSON.parse(msg.body);
});
},
function(error) {
// A connection error occurs
console.log('failure');
console.log(error); }); },Copy the code