当前位置:网站首页>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
边栏推荐
- Common software shortcuts
- Compiler introduction
- JVM memory area
- 面试题 17.11. 单词距离 ●●
- IPv4 addresses have been completely exhausted, and the Internet can work normally. NAT is the greatest contributor!
- Use of qvariant
- [database learning] redis parser & single thread & Model
- Qt的TQTreeWidget控件
- 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
- 数据平台下的数据治理
猜你喜欢

Xiaobai programmer's seventh day

Day006 select structure (if statement exercise)

Share two music playing addresses

面试题 17.11. 单词距离 ●●
![[training day15] simple calculation [tree array] [mathematics]](/img/20/a5604f666ab02f47929f80c5597f0a.png)
[training day15] simple calculation [tree array] [mathematics]

Pyspark data analysis basis: pyspark.sql.sparksession class method explanation and operation + code display

【集训DAY12】Bee GO!【动态规划】【数学】

【集训DAY13】Travel【暴力】【动态规划】

Simple setting method of search box

Anaconda~Upload did not complete.
随机推荐
【集训DAY13】Out race【数学】【动态规划】
Short circuit and &, short circuit or |, logic and &, logic or |; Conditional operator
BIO、NIO、AIO的区别?
Domain oriented model programming
Arcgis10.2 configuring postgresql9.2 standard tutorial
Build commercial projects based on ruoyi framework
新媒体运营策略(以小红书为例)帮助你快速掌握爆款创作方法
[training day13] backpack [dynamic planning] [greed]
[training Day11] Nescafe [greed]
沃达德软件:智慧城市方案
Use of qvariant
武汉理工大学第三届程序设计竞赛 B-拯救DAG王国(拓扑性质处理可达性统计问题)
【集训DAY12】树!树!树!【贪心】【最小生成树】
【Leetcode】502.IPO(困难)
If jimureport building block report is integrated according to the framework
[MySQL rights] UDF rights (with Malaysia)
IPv4 addresses have been completely exhausted, and the Internet can work normally. NAT is the greatest contributor!
QT log file system
[training day15] simple calculation [tree array] [mathematics]
JVM memory area