当前位置:网站首页>Websocket summary
Websocket summary
2022-07-25 22:43:00 【Cabbage 00】
Catalog
contrast http Similarities and differences of protocol request format
be based on node.js Of websocket modular
websocket Introduce
WebSocket It's a network Communication protocol , yes HTML5 Start by offering one in a single TCP A protocol for full duplex communication on a connection .RFC6455 It defines its communication standard .
http And websocket
- HTTP Protocol is a typical client request , Server response protocol ( The server will never send messages directly to the client , Unless the client requests )
- websocket Full duplex (Full Duplex) Communication transmission allows data to be transmitted simultaneously in both directions , Either party can take the initiative to send messages to the other party .

Be careful
- websocket It's not a new agreement , It is Take advantage of http Protocol to establish a connection
- websocket The connection must be initiated by the browser , Because the request protocol is a standard http agreement
Why? websocket The connection can realize full duplex communication http Connection is not possible
http The agreement is based on TCP Above the agreement ,TCP The protocol itself has full duplex communication , but http The request response mechanism of the protocol restricts full duplex communication .websocket After the connection is established , In fact, it simply stipulates that communication is not used http It's agreed , Send data directly to each other
websocket Request format

contrast http Similarities and differences of protocol request format
- The request address is not similar /path/, But rather ws:// The address at the beginning
- Request header upgrade:websocket and connection:upgrade Indicates that this connection will be converted to websocket Connect
- sec-websocket-key Used to identify this connection , Not for encrypting data
- sec-websocket-version It specifies websocket Version number of
websocket The response format

Be careful
- The response code above 101 Indicates the http The agreement is about to be changed , The changed agreement is upgrade:websocket designated websocket agreement
- The version number and sub agreement specify the data format that both parties can understand , And whether it supports compression and so on , If only websocket Of API You don't need to care about these
- One websocket The connection is established successfully , Browsers and servers can actively send messages to each other at any time . The news is 2 Kind of , One is text , One is binary data , Usually , We can send JSON Formatted text , This is very easy to handle in the browser
- Safe websocket Connection mechanism and https similar . First , Browser use wss://xxx establish websocket When the connection , Will pass first https Create a secure connection , then , The https Connection upgrade to websocket Connect , The bottom communication is still safe SSL/TLS agreement
- websocket The protocol may not support some browsers with lower versions
be based on node.js Of websocket modular
- ws modular
- socket.io modular
ws modular
npm initialization :npm init
install ws modular :npm i ws
Common scenarios : One server serves multiple clients
Server side
const express=require("express")
const app=express()
app.use(express.static("./public"))
//http Respond to
app.get("/",(req,res)=>{
res.send({ok:1})
})
app.listen(5000)
//websocket Respond to
const {WebSocket}=require("ws")
const wss=new WebSocket.WebSocketServer({port:8080})
wss.on('connection',function connection(ws){
ws.on('message',function message(data){
console.log(" received :%s",data);
// Forward to others
wss.clients.forEach(function each(client){
if(client!==ws&&client.readyState===WebSocket.OPEN){
client.send(data,{binary:false})
}
})
})
ws.send(' Welcome to the chat room ')
// Triggered when a client disconnects
ws.on("close",()=>{
console.log(" The handsome boy is gone ");
})
})client
//chat.html In the file
<body>
<h1> Chat client </h1>
</body>
<script>
// establish websocket Connect
var ws=new WebSocket("ws://localhost:8080")
// Open the callback function after the connection is successful
ws.onopen=function(){
console.log(" Successful connection ");
// Send a message
ws.send("hello world")
}
// The callback function triggered every time the server sends a message
ws.onmessage=function(msgObj){
console.log(msgObj.data);
}
// Go when the connection fails onerror Callback function
ws.onerror=function(){
console.log(" The connection fails ");
}
// Callback function when the server goes down
ws.onclose=function(){
console.log(" Server down ");
}
</script>Be careful : The static folder is public, There are chat.html page
socket.io modular
npm initialization :npm init
install socket.io modular :npm i socket.io
Server side
// Server side
const http=require("http")
const fs=require("fs")
const app=http.createServer()
app.on("request",(req,res)=>{
fs.readFile(__dirname+"/index.html",function(err,data){
if(err){
res.writeHead(500)
return res.end("Error loading index.html")
}
res.writeHead(200)
res.end(data)
})
})
app.listen(3000,()=>{
console.log("server start");
})
// The following code must be introduced in app Listen to the back of the port
const io=require("socket.io")(app)
// Listen to the event of user connection , As long as the user is connected , This event will be triggered
//socket Indicates the user's connection ,socket.emit Indicates that an event is triggered ,socket.on It means listening to an event
io.on("connection",socket=>{
console.log(" New users are connected ");
//socket.emit The method of should be used to send data to the browser
// Parameters 1: Event name - Write your name at will
// The server sends data to the client
socket.emit("get",{name:"cjc"})
// The server receives data from the client
socket.on("send",data=>{
console.log(data);
})
})client
introduce socket.io.js file :<script src="/socket.io/socket.io.js"></script>
<!-- index.html In page -->
<body>
<script src="/socket.io/socket.io.js"></script>
<h1>node.js The chat room </h1>
<script>
// Connect socket service , The parameter is the server address
var socket=io("http://localhost:3000")
// Receive the data returned by the server
socket.on("get",data=>{
console.log(data);
})
// Send data to the server
socket.emit("send"," I want to send data ")
</script>
</body>visit :http://localhost:3000/
Be careful :
- socket.io Useful to websocket agreement , But for not supporting websocket Your browser will fall back to http The polling , And provide automatic reconnection , and ws There is no such support
- socket.io The data transmission object and string of the module can ,ws Module data transmission can only be string
边栏推荐
- Naming rules of software test pytest pytest the pre and post confitest of use cases Py customized allure report @pytest.mark.parameter() decorator as data-driven
- Tree view model example of QT
- scrapy无缝对接布隆过滤器
- 平台架构搭建
- Learning orientation today
- Dom and events
- Xiaobai programmer's sixth day
- According to the use and configuration of data permissions in the open source framework
- 【集训DAY13】Out race【数学】【动态规划】
- Select structure if branch structure
猜你喜欢

xss-工具-Beef-Xss安装以及使用

Examples and points for attention about the use of getchar and scanf

Xiaobai programmer day 8
![[MySQL rights] UDF rights (with Malaysia)](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
[MySQL rights] UDF rights (with Malaysia)

对需求的内容进行jieba分词并按词频排序输出excel文档

JSON object

We media people must have four resource tools, each of which is very practical

我们为什么要推出Getaverse?

1000个Okaleido Tiger首发上线Binance NFT,引发抢购热潮

Two methods of printing strings in reverse order in C language
随机推荐
Kibana~后台启动Kibana之后无法找到进程号
Today, learn about the use of lists, hyperlinks, image tags, and audio and video
Data governance under data platform
自媒体人必备的4个资源工具,每一个都很实用
分割金条的代价
[training Day11] Calc [mathematics]
[MySQL rights] UDF rights (with Malaysia)
冯诺依曼体系结构
【集训DAY15】好名字【hash】
【集训DAY12】Minn ratio 【dfs】【最小生成树】
Five constraints and three paradigms
Data type conversion
Pyspark data analysis basis: pyspark.sql.sparksession class method explanation and operation + code display
为啥谷歌的内部工具不适合你?
Arcgis10.2 configuring postgresql9.2 standard tutorial
数据平台下的数据治理
Data quality: the core of data governance
ECMA 262 12 Lexical Grammer
Build commercial projects based on ruoyi framework
【PMP学习笔记】第1章 PMP体系引论