Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use socket.io to realize a Real-time Communication Application in node.js

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, the editor will share with you how to use socket.io to achieve a real-time communication application in node.js. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

WebSocket concept

Different from HTTP half-duplex protocol, WebSocket is a full-duplex protocol based on TCP connection, which supports two-way communication between client and server.

WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In WebSocket API, only one handshake is needed between the browser and the server, and a persistent connection can be directly created between the browser and the server for two-way data transmission.

In WebSocket API, the browser and the server only need to shake hands, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.

Realize

Native implementation

The WebSocket object supports a total of four messages onopen, onmessage, onclose, and onerror.

Establish a connection

Through javascript, you can quickly establish a WebSocket connection:

Var Socket = new WebSocket (url, [protocol])

The first parameter in the above code, url, specifies the URL of the connection. The second parameter, protocol, is optional and specifies an acceptable subprotocol.

Just as the http protocol begins with http://, the URL of the WebSocket protocol begins with ws://, and the secure WebSocket protocol begins with wss://.

An onopen message is triggered when the Browser and WebSocketServer connections are successful.

Socket.onopen = function (evt) {}

If the connection fails, if you fail to send or receive data, or if there is an error in processing the data, browser triggers an onerror message.

Socket.onerror = function (evt) {}

The onclose message is triggered when the Browser receives a request to close the connection sent by the WebSocketServer side.

Socket.onclose = function (evt) {}

Send and receive messages

When Browser receives the data sent by WebSocketServer, it triggers the onmessage message, and the parameter evt contains the data transmitted by server.

Socket.onmessage = function (evt) {}

Send is used to send messages to the server.

Socket.send ()

Socket

WebSocket was proposed along with HTML5, so there was a problem with compatibility, and a very useful library came out-- Socket.io.

Socket.io encapsulates websocket, as well as other connection methods, and you can use socket.io to establish asynchronous connections in any browser. Socket.io contains libraries for both the server and the client, and if socket.io 's js is used in the browser, the server must also be applicable.

Socket.io is a Client-Server real-time communication library based on Websocket.

The underlying socket.io is based on the library engine.io. Engine.io provides socket.io with an underlayer library for cross-browser / cross-device two-way communication. Engine.io encapsulates a set of socket protocols using Websocket and XHR. In earlier versions of browsers, Websocket is not supported and long polling (polling) alternatives are used for compatibility.

API document

Socket.io allows you to trigger or respond to custom events, and you can trigger any custom event name except connect,message,disconnect whose names cannot be used.

Establish a connection

Const socket = io ("ws://0.0.0.0:port"); / / port for its own defined port number let io = require ("socket.io") (http); io.on ("connection", function (socket) {})

Send and receive messages

First, send data

Socket.emit (custom sent field, data)

Second, receive data

Socket.on (custom sent field, function (data) {console.log (data);})

Disconnect

1. Disconnect all

Let io = require ("socket.io") (http); io.close ()

Second, a client breaks the link with the server

/ / client socket.emit ("close", {}); / / server socket.on ("close", data = > {socket.disconnect (true);})

Room and namespace

Sometimes websocket has the following usage scenarios: 1. The messages sent by the server are classified, and different clients need to receive different categories; 2. The server does not need to send messages to all clients, just to a specific group

For this usage scenario, namespace and room, which are very useful in socket, come on.

Let's take a look at the relationship between namespace and room:

Namespace

Server side

Io.of ("/ post") .on ("connection", function (socket) {socket.emit ("new message", {mess: `this is the namespace of post`}); io.of ("/ get") .on ("connection", function (socket) {socket.emit ("new message", {mess: `this is the namespace of get`});})

Client

/ / index.js const socket = io ("ws://0.0.0.0:****/post"); socket.on ("new message", function (data) {console.log ('index',data);} / / message.js const socket = io ("ws://0.0.0.0:****/get"); socket.on ("new message", function (data) {console.log (' message',data);}

Room

Client

/ / can be used for the client to enter the room; socket.join ('room one'); / / to leave the room; socket.leave (' room one')

Server side

Io.sockets.on ('connection',function (socket) {/ / submitters will be excluded (i.e. will not receive messages) socket.broadcast.to (' room one'). Emit ('new messages', data); / / send messages io.sockets.to (data) .emit ("recive message", "hello, users in the room") to all users;}

An example of receiving information in real time with socket.io

Finally to the application stage, the server uses node.js to simulate the server interface. The following examples are implemented on the local server.

Server side

First, let's take a look at the server. First, let's start a service and install express and socket.io.

Installation dependency

Npm install-Dev expressnpm install-Dev socket.io

Build a node server

Let app = require ("express") (); let http = require ("http") .createServer (handler); let io = require ("socket.io") (http); let fs = require ("fs"); http.listen (port); / / port: enter the required port number function handler (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);} io.on ("connection", function (socket) {console.log ("connection successful"); / / send a message socket.emit ("new message", {mess: `initial message `}) after a successful connection;})

Client

Core code-index.html (sending data to the server)

The transmitted frame data can be viewed in the Frames.

What does the number in front of the frame data mean?

This is the Engine.io protocol, where the digits are packet codes:

[]

0 open-- is sent from the server when a new transfer is opened (recheck)

1 close-- requests to close this transfer, but does not close the connection itself.

2 ping-- is sent by the client. The server should reply with a pong packet containing the same data

Sent by client: 2probe probe Fram

3 pong-- is sent by the server in response to the ping packet.

Server sends: 3probe, response client

4 message-- the actual message, the client and server should use the data to invoke their callback.

5 upgrade-- tests if the server and client can communicate through this transport before engine.io switches the transmission. If this test is successful, the client sends an upgrade packet, requesting the server to refresh its cache on the old transport and switch to the new one.

6 noop--noop packets. Used primarily to force polling cycles when incoming WebSocket connections are received.

Example

The screenshot above is an example of data transmission in the above example. The approximate process is as follows:

Connect handshake succeeded

The client sends a 2 probe probe frame

The server sends a response frame 3probe

The client sends a Upgrade frame with a content of 5

The server responds to the noop frame with content 6

After the probe frame check passes, the client stops polling the request, transfers the transport channel to the websocket connection, transfers to websocket, and then starts the regular (default is 25 seconds) ping/pong.

The client and the server send and receive data. 4 represents the message message of engine.io, followed by the content of the message.

In order to know whether the Client and Server links are normal, both ClientSocket and ServerSocket used in the project have a heartbeat thread, which is mainly used to detect whether Client and Server are properly linked, and whether Client and Server are properly linked is mainly guaranteed by ping pong process.

The interval at which the heartbeat is sent periodically is 25m as set by default by socket.io, which can also be observed in the image above. The interval can be modified through configuration.

These are all the contents of the article "how to use socket.io to achieve a real-time communication application in node.js". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report