knowledge
-
Front end cycle to obtain data
-
The SERVER send Event (SSE) server pushes data.
-
The websocket protocol
-
Nodejs uses socket. IO module to realize long connection.
-
Web version chat system;
The target
- Understand the meaning of data push
- Learn SSE to implement data push
- Understand the WebSocket protocol
- Can use socket. IO module
Front end cycle to obtain data
- The front wheel circulates to obtain data;
- Loop through ajax requests to get data
- Consume performance, consume resources, not recommended;
The SERVER send Event (SSE) server pushes data.
Server-sent Events: Using the method of server-sent events, the Server can push data and information to our Web page at any time. The information that is pushed in can be treated as event +data on this page.
-
Server Settings
-
Set up the head
"Content-type","text/event-stream"
-
Returned data format
Data: Declares the start of data
\r\n\r\n indicates the end of the data
-
-
Front end access
let source = new EventSource("/test"); source.onopen = function(){ console.log("Connection established...".this.readyState); } // console.log(source) source.onmessage = function(evnet){ console.log("The data are:",evnet.data) } source.error = function(err){ return console.log('err'); } Copy the code
- ReadyState stands for connection status:
- 0
CONNECTING
(0
). - 1
OPEN
(1
), - 2 CLOSED
(
2 `)
- 0
- ReadyState stands for connection status:
websocket
-
WebSocket is a protocol for full duplex communication on a single TCP connection provided by HTML5.
-
Create a Websocket server;
var WebSocketServer = require('ws').Server, wss = new WebSocketServer({ port: 8181 }); wss.on('connection'.function (ws) { console.log('client connected'); ws.on('message'.function (message) { // Listen for received data console.log(message); }); setInterval((a)= > { let somedata = { name:"Zhang".age:20 } ws.send(JSON.stringify(somedata)); }, 1000); }); Copy the code
-
Client code
- Set up to shake hands
var ws = new WebSocket("ws://localhost:8181"); Copy the code
Open the agreement
ws.onopen = function () {} Copy the code
- Sends data to the server
ws.send("Client data"); Copy the code
- Disable protocol: No data can be sent after the protocol is disabled
ws.close(); Copy the code
-
Receives the message
ws.onmessage = function(e){ // console.log(e.data); } Copy the code
Socket. IO module
-
The service side
const server = require('http').createServer(app.callback()); const io = require('socket.io')(server); server.listen(3000); Copy the code
-
The client
let socket = io.connect(); this.emit("clientfn"."hello i am client"); socket.on("message".function(data){} Copy the code
conclusion
-
Front end cycle to obtain data
-
The SERVER send Event (SSE) server pushes data.
-
The websocket protocol
-
Nodejs uses socket. IO module to realize long connection.