This is the 11th day of my participation in the August More Text Challenge. For details, see:August is more challenging
The last article gave you the basics of WebScoket. This article will give you an example of how to use WebScoket. For those of you who haven’t seen the basic introduction, click on the link in the back. WebScoket basics
More articles on my Github and personal public number [Whole cliff Road], welcome to watch [front knowledge points], if there is benefit, don’t pay, little hands point a Star
This example is based on a vue-CLI project
Create ideas
The factory function pulls out
- Encapsulate Web Socket for instantiation and ease of use
Multiple Websockets need to be created under the same Vue instance
- Create with ES6 class
- Path can be custom passed to solve the problem of multiple ket connections created and existing at the same time
The WebScoket callback is handled separately
- The WebScoket Handler is mounted by creating the instance
- Mount functions are customized
The heartbeat detection
- Example Add public heartbeat detection
The Ready State
- The instance encapsulates the ReadyState state for easy access
Break line reconnection
- Disconnection reconnection is handled separately when using the example to facilitate service requirements
Code section
WebScoket part
- WebScoket needs to be flexible and scalable to inject the requested address through the node environment variable.
- The heartbeat problem that WebScoket needs to solve mentioned in the basic introduction is also added in the case of heartbeat detection, in which the heartbeat time of heartbeat detection needs to be mastered by the developers themselves, on the basis of not affecting the basic data transmission, select the appropriate heartbeat time.
- The heartbeat detection mechanism is to send heartbeat packets to the server through a socket link in accordance with the heartbeat detection period. At the same time, the server sends a response message back to ensure that the connection is normal and the two parties can normally transmit information.
- Expose the webket related property API as a whole for call processing in the business.
// scoket. Js const webscketurl = process.env.backend_URL // Set scoket path class WebSocketUtil{ constructor(wspath){ let protocol = (window.location.protocol == 'https:') ? 'wss://' : 'ws://'; Let wsuri = protocol + webscketurl + wspath // new instance this. Websock = new WebSocket(wsuri)} // heartCheck(){let self = this; If (this.timeoutobj){clearInterval(this.timeoutobj)} this.timeoutobj = setInterval(function(){if (this.timeoutobj){clearInterval(this.timeoutobj)} this.timeoutobj = setInterval(function(){ If (self.readyState()! = 1) { clearInterval(self.timeoutObj) } self.websock.send("HeartBeat"); Console. log("HeartBeat"); }, On (funName,handler){this.websock[' on${funName} '] = handler Send (MSG){this.websock. Send (MSG)} // Listen for websock link state readyState(){ Return this. Websocket.readystate; // Return this. Websocket.readystate; // Return this. } // Export the instance default WebSocketUtilCopy the code
Instance creation section
// index.vue import $WebSocketUtil from '.. /.. // instantiate chat scoket initScoket() {let token = this.$cookies. Get ('token') let pathData = '/chat? token=' + token this.webscoketChat = new $WebSocketUtil(pathData) this.webscoketChat.on('message', this.websocketonmessage) this.webscoketChat.on('open', this.websocketonpen) this.webscoketChat.on('error', this.websocketonerror) this.webscoketChat.on('close', this.websocketonerror) Vue.prototype.$scoketChat = this.webscoketChat }, / / socket set up after a successful start heartbeat detection websocketonpen () {this. WebscoketChat. HeartCheck ()}, Websocketonerror () {let self = this if (this.reconnectChat) {return} this.reconnectChat = true SetTimeout (function () {self.initscoket () console.log("Chat is reconnecting...") ) self.reConnectChat = false}, 10000)}, // Receive webSocket message webSocketonMessage (e) {let res = json.parse (e.ata); HandleChat(res.type,res.data,res.wxId || ''); },Copy the code
Write in the last
- If you know nothing about Web Socket, it is recommended that you first learn this article, The Basics of Web socket
- This example is only written according to their own needs and code logic, not necessarily suitable for all projects, need to be improved according to the actual situation, if you have better ideas, welcome to exchange [email protected]
Write in the last
If you find this article helpful, please like it and share it with more people who need it!
Welcome to pay attention to [Quanzhendaolu] and wechat public account [Quanzhendaolu], to get more good articles and free books!
There is a need [Baidu] & [bytedance] & [JD] & [ape counselling] within the push, please leave a message oh, you will enjoy the VIP level extreme speed within the push service ~
Past oliver
Wechat JS API payment implementation
Create a personalized Github profile
The interviewer asks you<img>
What elements do you say
Special JS floating point number storage and calculation
Long [word] baidu and good interview after containing the answer | the nuggets technology essay in the future
Front end practical regular expression & tips, all throw you 🏆 nuggets all technical essay | double festival special articles
HTML Tabindex
A few lines of code to teach you to solve wechat poster and TWO-DIMENSIONAL code generation
Vue3.0 Responsive data principle: ES6 Proxy
Read on to make your interviewer fall in love with you
How to draw a fine line gracefully
Front-end performance optimization -HTML, CSS, JS parts
Front-end performance optimization – Page loading speed optimization
Front-end performance optimization – Network transport layer optimization