当前位置:网站首页>Websocket (simple experience version)
Websocket (simple experience version)
2022-07-01 14:07:00 【Red blue purple】
WebSocket( Simple experience version )
brief introduction
Web Socket( Socket ): It is through A long-term connection Implementation and server full duplex 、 two-way Communication for .
Web Socket It's not that HTTP The protocol is customized Web Socket agreement , So if we use Web Socket When ,URL No more http:// or https://, It is ws:// or wss://( however , Actually, I just want to play after reading the Red Treasure book , I haven't tried to use this in development )
The main features : The server can actively push information to the client , The client can also send information to the server .
Use
Instantiation
To create a new Web Socket, First you need to instantiate a WebSocket object .
We instantiate WebSocket Object time , The parameter passed should be an absolute URL, The homology strategy does not apply to WebSocket
const socket = new WebSocket("ws://localhost:8088/mysocket");

http The request will have cross domain , however WebSocket No cross domain
Back end express
The main parts are annotated ( Need to install express-ws)
const express = require('express')
const expressWs = require('express-ws')
const app = express()
// take WebSocket Services added to app in , To put it simply, let app Added ws Method
expressWs(app)
// establish WebSocket service
app.ws('/mysocket', function (ws) {
// ws: establish WebSocket Example
// Send messages to clients
ws.send(' You are connected successfully ')
})
app.listen(8088, () => {
console.log('ws://localhost:8088')
})

If it's connected , that http The status code will be 101, Because I want to switch to ws agreement
The binding event
If we , Start sending messages after instantiation , That will cause the message not to be sent out , Because it's not connected yet . At this time, we have to find out when we can send , Then we have to understand WebSocket Related events .
open: Triggered when the connection is successfully establishederror: Triggered when a connection error occurs ( You can no longer send messages )close: Trigger... When the connection is closed ( You can no longer send messages )message: Trigger when you receive a message ( The received message is in the event objectdatain )
const socket = new WebSocket("ws://localhost:8088/mysocket");
socket.onopen = function () {
console.log(" Connection is established ");
socket.send('hello');
// socket.close()
};
socket.onerror = function () {
console.log(" Connection error ");
};
socket.onclose = function () {
console.log(" Connection is closed ");
};
socket.onmessage = function (e) {
console.log(e)
}


Simulate a conversation between two people
It's already said , Receiving a message triggers message event , So we can message In the event, the corresponding information is sent according to the received information .
client :
const socket = new WebSocket("ws://localhost:8088/mysocket");
socket.onopen = function () {
console.log(" Connection is established ");
socket.send('hello');
// socket.close()
};
socket.onerror = function () {
console.log(" Connection error ");
};
socket.onclose = function () {
console.log(" Connection is closed ");
};
socket.onmessage = function ({
data }) {
if (data.includes(' Hello ')) {
socket.send(' bye , Server side ddd')
} else if (data.includes(' bye ')) {
// call close() Method shut down WebSocket Connect
socket.close()
} else {
socket.send(' Hello , I'm the client ccc')
}
}
The server :
const express = require('express')
const expressWs = require('express-ws')
const app = express()
// take WebSocket Services added to app in , To put it simply, let app Added ws Method
expressWs(app)
// establish WebSocket service
app.ws('/mysocket', function (ws) {
// ws: establish WebSocket Example
ws.send(' You are connected successfully ')
ws.onmessage = function ({
data }) {
if (data.includes(' Hello ')) {
ws.send(' Hello , I'm the server ddd')
} else if (data.includes(' bye ')) {
ws.send(' bye , client ccc')
}
}
})
app.listen(8088, () => {
console.log('ws://localhost:8088')
})

Be careful : If the receiving and sending part processes , You need to pay attention to , If it's not handled properly , There may be a circulation jam .
such as , Server and client message Event callbacks are :
socket.onmessage = function ({
data }) {
socket.send('hello')
}

边栏推荐
猜你喜欢

Use the npoi package of net core 6 C to read excel Pictures in xlsx cells and stored to the specified server

After being laid off for three months, the interview ran into a wall everywhere, and the mentality has begun to collapse

Interpretation of R & D effectiveness measurement framework

清华章毓晋老师新书:2D视觉系统和图像技术(文末送5本)

用对场景,事半功倍!TDengine 的窗口查询功能及使用场景全介绍

Tdengine connector goes online Google Data Studio app store

So programmers make so much money doing private work? It's really delicious

Station B was scolded on the hot search..

当你真的学会DataBinding后,你会发现“这玩意真香”!

Scheme of printing statistical information in log
随机推荐
Using CMD to repair and recover virus infected files
sqlilabs less-11~12
Sign APK with command line
清华章毓晋老师新书:2D视觉系统和图像技术(文末送5本)
WebSocket(简单体验版)
sqlilabs less13
百度上找的期货公司安全吗?期货公司怎么确定正规
JVM有哪些类加载机制?
佩服,阿里女程序卧底 500 多个黑产群……
Etcd 概要 机制 和使用场景
那个很努力的学生,高考失败了……别慌!你还有一次逆袭机会!
Scheme of printing statistical information in log
GET请求如何传递数组参数
Effet halo - qui dit qu'il y a de la lumière sur la tête est un héros
开源实习经验分享:openEuler软件包加固测试
Applet - multiple text line breaks in view
Tdengine connector goes online Google Data Studio app store
使用 Lambda 函数URL + CloudFront 实现S3镜像回源
原来程序员搞私活这么赚钱?真的太香了
ArrayList capacity expansion mechanism and thread safety