当前位置:网站首页>Websocket (simple experience version)
Websocket (simple experience version)
2022-06-28 03:28: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')
}

边栏推荐
- collections.defaultdict()的使用
- A16z: metauniverse unlocks new opportunities in game infrastructure
- 【PaddleDetection】ModuleNotFoundError: No module named ‘paddle‘
- SSH框架的搭建(上)
- Apache——阿帕奇簡介
- 导入Excel文件,解决跳过空白单元格不读取,并且下标前移的问题,以及RETURN_BLANK_AS_NULL报红
- No result defined&nbsp…
- What is the best and safest software to download when buying stocks?
- Notepad++--列编辑模式--用法/实例
- Windows 2003 64 bit system PHP running error: 1% is not a valid Win32 Application
猜你喜欢

音视频技术开发周刊 | 251
![[iptables & ICMP] description of ICMP Protocol in iptables default policy](/img/9d/85027ea0b0bc9c6494ba41daed9f38.png)
[iptables & ICMP] description of ICMP Protocol in iptables default policy

導入Excel文件,解决跳過空白單元格不讀取,並且下標前移的問題,以及RETURN_BLANK_AS_NULL報紅

自用工具 猴子都会用的unity视频播放器

collections. Use of defaultdict()

第二轮红队免费公开课来袭~明晚八点!

Redis搭建集群【简单】

Etcd database source code analysis -- network layer server rafthandler between clusters

爱普生L3153打印机如何清洗喷头

Basic operation of stack (implemented in C language)
随机推荐
2022安全员-C证考试题库模拟考试平台操作
Solution to not displaying logcat logs during debugging of glory V8 real machine
__getitem__和__setitem__
nn. Parameter and torch nn. Init series of functions to initialize model parameters
Is it better for a novice to open a securities account? Is it safe to open a stock trading account
学习---有用的资源
荣耀v8 真机调试时不显示 Logcat 日志的解决办法
Necessary software tools in embedded software development
如何获取GC(垃圾回收器)的STW(暂停)时间?
Win 10出现bitlocke恢复,蓝屏错误代码0x1600007e
Object类,以及__new__,__init__,__setattr__,__dict__
数的每一位平方和
剑指 Offer 53 - I. 在排序数组中查找数字 I(改进二分)
idea自动生成代码
Import an excel file, solve the problem of skipping blank cells without reading and moving the subscript forward, and return_ BLANK_ AS_ Null red
JS clear the object and its value:
2022危险化学品经营单位安全管理人员特种作业证考试题库模拟考试平台操作
Simple elk configuration to realize production level log collection and query practice
《Go题库·12》slice和array区别?
用于 C# 的 SQL 基本语法总结