Use Socket. io to push messages in real time, and socket. io to push messages in real time.

Source: Internet
Author: User
Tags node server

Use Socket. io to push messages in real time, and socket. io to push messages in real time.

Project Background

There is a social network module in a recently written project. You need to implement this function: when a user is liked, commented, or followed, the server needs to push a message to the user in real time. The final project address is https://github.com/noiron/socket-message-push. here we will introduce the actual thinking and coding code.

There are several objects in the project process:

  • Backend servers implemented in Java
  • Message pushing server implemented by Node. js
  • Client for user operations

The event processing process is as follows:

  • The backend server processes the like and sends a message to the Node. js message pushing server.
  • The Node. js message pushing server processes data after receiving the message sent from the backend and determines the user to which the message is pushed.
  • After receiving messages pushed by the Node. js server, your client can display the notifications.
  • In the above process, how Java backend servers are implemented is not covered in this article. This article will mainly introduce how to use Node. js to implement this message push server.

The message pushing server must record the information of the current online user to push messages to a specific user. Therefore, when a user logs on, the user information must be sent to the Node. js server. To achieve this two-way real-time message transmission, we obviously consider using WebSocket. Since we use Node. js on the message pushing server, we have a very convenient option: socket. io.

Socket. io Introduction

Socket. io is a library for real-time two-way communication implemented by JavaScript. It is very easy to use it to implement our functions.

Socket. io contains two parts:

  • Server: runs on the Node. js server.
  • Client: running in a browser

Let's take a look at the following socket. io sample code, which provides the basic usage of socket. io sending and listening events:

io.on('connection', function(socket){ socket.emit('request', /* */); // emit an event to the socket io.emit('broadcast', /* */); // emit an event to all connected sockets socket.on('reply', function(){ /* */ }); // listen to the event});

Note that Socket. io is not fully implemented by WebSocket.

Note: Socket. IO is not a WebSocket implementation. although Socket. IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the ack id when a message acknowledgement is needed.
Next, we need to use Express. js to create a server-side program and introduce Socket. io.

Node. js server Construction

Use Express. js to build basic servers

We use Express. js to build a Node. js message push server. First, we use a brief example to view its functions:

// server.jsconst express = require('express');const app = express();const path = require('path');const http = require('http').Server(app);const port = 4001;app.use(express.static(path.join(__dirname, 'public')));app.get('/', function(req, res) { res.sendFile(__dirname + '/public/index.html');});app.get('/api', function(req, res) { res.send('.');});http.listen(port, function() { console.log(`listening on port:${port}`);});

Save the above Code as server. js, create a public folder, and put the index.html file in it. Run the following command:

node server.js

Now you can view the effect on localhost: 4001.

Introduce Socket. io

Now that you have a basic Express server, you need to add Socket. io to it.

const io = require('socket.io')(http);io.on('connection', function(socket) { console.log('a user connected'); socket.broadcast.emit('new_user', {});}

Here I/O listens for connection events. After the client establishes a connection with the server, the callback function will be called (the code in the client will be introduced in the next section ).

The socket parameter of the function indicates the connection established between the current client and the server. You can print the established socket connection in the client program, as shown in:

The id attribute can be used to identify the connection, so that the server can send messages to specific users.

socket.broadcast.emit('new_user', {});

This line of code indicates that the socket will broadcast a message named new_user to all the clients (not including themselves) that have established connections with the server.

Process of pushing messages at the backend

  • Create a ing table between user information and socket id on the Node server. Because the same user may open multiple pages, his socket id may have multiple values. When a user establishes a connection, add a value to it. When the user disconnects, delete the value.
  • When a message needs to be pushed in the Java background, a message is sent to the Node server/api path, including the tokenId used to identify the user and other data.
  • After receiving the post request, the Node server processes the request content. Find the socket id corresponding to the user based on the tokenId, and socket. io will push messages to the user based on the id.

Processing user information

For convenience, only one array is used to save user information. You can store user information in the database as needed.

Global. users = []; // record the tokenId and socketId of the logged-on user

When a user logs on, the client sends the user_login event to the server. After receiving the event, the server performs the following operations:

socket.on('user_login', function(info) { const { tokenId, userId, socketId } = info; addSocketId(users, { tokenId, socketId, userId });});

AddSocketId () adds user information to the users array. Different users are differentiated by tokenId. each user has a socketIds array to save multiple possible socketIds. The specific code of this function can be seen in the src/utils. js file.

Similarly, there is also a deleteSocketId () function used to delete user information, the code can be seen in the same file.

After obtaining the user's tokenId, you need to find the corresponding socketId and then push the message to the specific user.

// Send the io. sockets. to (socketId). emit ('receive _ message', {entityType, data}) message only to the connection with id = socketId });

The idea of the server is roughly the same. Next we will introduce how to handle the problem on the client.

Client

Socket. io Initialization

First, introduce the Socket. io client file into the html file, for example, introduce the file through CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>

Other import methods:

<script src="/socket.io/socket.io.js"></script>const io = require('socket.io-client');// or with import syntaximport io from 'socket.io-client';

After Socket. io is introduced, I/O functions are obtained to establish a connection with the message push server.

// Assume that the address after you deploy the Node server is: https://www.example.com/ws//, then: WS_HOST = 'https: // www.example.com 'const msgSocket = io (' $ {WS_HOST} ', {secure: true, path: '/ws/socket. io '});

If the listener is local:

const msgSocket = io('http://localhost:4001');

Here, if I/O is written ('https: // www.example.com/ws'), an error occurs and/ws must be written to the path.

To use this variable in other files, you can use msgSocket as a global variable:

window.msgSocket = msgSocket;

Establish a connection

// Send user information to the server during user logon. After receiving the information, the server establishes a ing between the socket and the user. MsgSocket. emit ('user _ login', {userId, socketId: msgSocket. id, tokenId });

Processing after receiving pushed messages

// After a WebSocket connection is established, listen to the event msgSocket named receive_message. on ('receive _ message', msg => {store. dispatch ({type: 'New _ SOCKET_MSG ', payload: msg });});

After the WebSocket server pushes a message to the client, the client needs to listen to the receive_message event and the received parameters contain the information to be processed.

Due to the use of Redux for data processing, here dispatch a NEW_SOCKET_MSG action, followed by a conventional redux processing process.

Project usage

GitHub Project address: https://github.com/noiron/socket-message-push

npm run dev

You can perform the test in the devlopment environment. Now you have a message push server running on port 4001.

However, there is no backend server to send messages to us, so we will use Postman to simulate sending messages.

To display the functions of a program, an index.html file is placed under the client folder of the project. Note that this file cannot be used in actual projects, but is used to display the message push effect.

After the server is enabled, open client/index.html and enter a tokenId as prompted.

Now post the following information to localhost: 4001/api using Postman:

{// The tokens array indicates the user to which You want to push the message "tokens": ["1", "2"], "data": "You shall not pass !!! "}

Now, if everything goes well, you should be able to see the received message on the client console.

You can open multiple client pages, enter different tokenids, and check whether the message is sent to the correct user.

Summary

The above section describes how to use Socket. i/O can push messages in real time. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.