Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use WebSocket gracefully

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "how to use WebSocket elegantly", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use WebSocket elegantly" article.

Brief introduction

Websocket is a two-way communication protocol based on TCP. Prior to this, polling has been used for two-way communication, which is inefficient and a waste of resources. In order to solve this problem, websocket came into being.

Characteristics

Two-way communication: websocket makes it easier to exchange data between the client and the server. Allows the server to actively push data to the client. The browser only needs to complete a handshake with the server to create a persistent connection and transfer data in both directions.

Strong real-time: the server can actively push data to the client. Compared with the http request, the browser will respond only after the client initiates the request. The delay is significantly less and the time is shorter.

Connection retention: after a successful websocket connection is created, communication will be maintained as long as the connection continues to open, and some status information will be omitted (http requests may need to carry status information for each request)

Working with scen

The advantages over http,websocket are obvious. Therefore, in some real-time communications, we need to use websocket, such as multimedia chat, player games, local page refresh, collaborative editing and other scenarios.

Concrete realization

After introducing what websocket is, let's show you how to implement websocket.

First, the first is the server code, here I use nodejs.

1. Let's create a new websocket.js file.

/ / create websocket service const port = "8888" const ws = require ('nodejs-websocket'); const web_server = ws.createServer (function (conn) {conn.on (' text', function (text) {console.log ("sent message", text); conn.sendText (`sent successfully, the message sent is: ${text} `)}) Conn.on ('close', function (code, reason) {console.log (' close the connection');}); conn.on ('error', function (code, reason) {console.log (' abnormal close');});}) .closed (port); exports.web_server = web_server

2. Introduce it into app.js

Const websocket = require (". / websocket")

3. Finally start the service

Node app 2, then the client code

① is used in vue

1. Let's create a new websocket.js file under utils.

Let webSocket = null;let socketOpen = false;// send message export const doSend = (message) = > {if (socketOpen) {webSocket.send (message)}} / / initialization websocketexport const contactSocket = () > {if ("WebSocket" in window) {webSocket = new WebSocket ("ws://192.168.1.100:8888/"); webSocket.onopen = function () {console.log ("connection successful!") ; socketOpen = true}; webSocket.onmessage = function (evt) {var received_msg = evt.data; console.log ("accept message:" + received_msg);}; webSocket.onclose = function () {console.log ("connection closed!") ;}

2. Page introduction file

Import {contactSocket, doSend} from'@ / utils/contactSocket'

3. Specific use examples

/ / initialize websocketcontactSocket () / / send message content setTimeout (() = > {doSend ("messages sent to the server")}, 1000)

② is used in uniapp

1. Let's create a new websocket.js file under the utils folder.

Let socketOpen = false;// send message function doSend (message) {if (socketOpen) {uni.sendSocketMessage ({data: message});}} / initialize websocketfunction contactSocket () {/ / establish connection uni.connectSocket ({url: 'ws://192.168.1.100:8888/'}) / / connection error uni.onSocketError (function (res) {console.log ('WebSocket connection failed to open, please check!') ;}); / / opened the connection uni.onSocketOpen (function () {console.log ('WebSocket connection is open!') ; socketOpen = true;}); / / close the connection uni.onSocketClose (function (res) {console.log ('WebSocket is closed!') ;}); / / accept the message uni.onSocketMessage (function (res) {console.log ('received server content:' + res.data);});} module.exports = {doSend, websocketInit}

2. Page introduction file

Import {doSend, contactSocket} from'@ / utils/websocket.js'

3. Specific use examples

/ / initialize websocketcontactSocket () / / send message content setTimeout (() = > {doSend ("message sent to the server");}, 1000) the above is about "how to use WebSocket gracefully". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about it, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report