当前位置:网站首页>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 objectdata
in )
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')
}
边栏推荐
- 【剑指Offer】54. 二叉搜索树的第k大节点
- Use the right scene, get twice the result with half the effort! Full introduction to the window query function and usage scenarios of tdengine
- Use lambda function URL + cloudfront to realize S3 image back to source
- Basic concepts of programming
- When you really learn databinding, you will find "this thing is really fragrant"!
- SWT / anr problem - how to capture performance trace
- Oracle-数据库对象的使用
- How can we protect our passwords?
- 2022上半年英特尔有哪些“硬核创新”?看这张图就知道了!
- Distributed dynamic (collaborative) rendering / function runtime based on computing power driven, data and function collaboration
猜你喜欢
用对场景,事半功倍!TDengine 的窗口查询功能及使用场景全介绍
Introduction to distributed transactions (Seata)
sqlilabs less9
[241. Design priority for operation expression]
Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of its
This paper introduces an implementation scheme to enhance the favorite transaction code management tool in SAP GUI
【IoT毕设.下】STM32+机智云AIoT+实验室安全监控系统
奔涌而来的数字化浪潮,将怎样颠覆未来?
Scheme of printing statistical information in log
开源实习经验分享:openEuler软件包加固测试
随机推荐
How to pass array parameters in get request
光環效應——誰說頭上有光的就算英雄
JVM有哪些类加载机制?
How will the surging tide of digitalization overturn the future?
2022. Let me take you from getting started to mastering jetpack architecture components - lifecycle
2022 PMP project management examination agile knowledge points (6)
Effet halo - qui dit qu'il y a de la lumière sur la tête est un héros
QT community management system
Halo effect - who says that those with light on their heads are heroes
Six years of technology iteration, challenges and exploration of Alibaba's globalization and compliance
So programmers make so much money doing private work? It's really delicious
Station B was scolded on the hot search..
8款最佳实践,保护你的 IaC 安全!
Scheme of printing statistical information in log
C语言订餐管理系统
That hard-working student failed the college entrance examination... Don't panic! You have another chance to counter attack!
[IOT completion. Part 2] stm32+ smart cloud aiot+ laboratory security monitoring system
3.4 data query in introduction to database system - select (single table query, connection query, nested query, set query, multi table query)
uni-app实现广告滚动条
Play with grpc - communication between different programming languages