Оcenka-BEL.com - безплатни онлайн тестове, пробни изпити, видео уроци и помощ при писане на задания от литературно и хуманитарно естество

How to Create Real-time Chat Application with Node.js Part 3

Публикувано: 2018-09-29 18:45:24

The back-end of the chat First we load the express module and set the port to be equal to process.env.PORT (which will be an environment variable defined by Heroku) or 8080 if we are on localhost. Then we create our Express server which will respond to HTTP requests. We load the html entities module, set Socket.IO to listen to our server and require Redis. Theredis.createClient takes as its first argument the port the database is on and as a second argument – the host it is on.

Create Real-time Chat Application with Node

DEMO

We provide the values given to us by Redis Labs and useclient.auth(‘password’, callback)to authenticate ourselves to the database with the password given to us by Redis Labs.

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

varexpress = require("express");

varport = process.env.PORT || 8080;

varapp = express();

varserver = app.listen(port, function() {

console.log("Server running");

})

 

varEntities = require("html-entities").XmlEntities,

entities = new Entities();

vario= require('socket.io').listen(server);

varredis= require("redis"),

client = redis.createClient(15288,'pub-redis-16297.us-east-1-3.6.ex5.redislabs.com',{no_ready_check: true});

client.auth('mySecretPassword', function (err) {

if (err) throw err;

});

Then, we set up the folder for static files to be called public with: app.use(express.static(“public”));

 

1

app.use(express.static("public"));

Afterwards, we insert our application logic nested within the callbacks that tell usthat we have a connection with Redis and that Socket.IO has connected the client:

 

1

2

3

4

5

6

7

client.on('connect', function() {

 

console.log('connected');

io.on('connection', function (socket) {

    //logic here

});

});

When a user joins, we add the entity encoded nickname to the database and set the name to that socket. Finally, we get all nicknames by telling Redis to give us values from index 0 to index -1 with:

 

1

2

3

client.lrange('nicknames', 0, -1, function (err, NICKNAMES) {

// do something with the data

});

After we get all the nicknames, we emit them to the client from the server with io.sockets.emit(‘eventName’, valueToPass);

All this happens only if the user’s name consists of less than 25 characters.

 

1

2

3

4

5

6

7

8

socket.on("join", function (data) {

if (data.length<= 25) {

client.lpush("nicknames", entities.encode(data));

socket.nickname=  entities.encode(data);

client.lrange('nicknames', 0, -1, function (err, result) {

io.sockets.emit('online', result);

        });

    }

We also get all messages when the user joins using the same lrange method and emit multiple events for each message stored there using a loop (in the callback):

 

1

2

3

4

5

6

client.lrange('messages', 0, -1, function (err, messages) {

for (vari= messages.length- 1; i>= 0; i--) {

socket.emit('incomingMessage', messages[i]);

        }

    })

})

Near the end, when the client sends to the server a message event we check if the message contains less than 100 characters and if the nickname has 25 characters or less and if so we add the message to Redis using lpush(‘key’, ‘value’).

If the criteria mentioned above are met, we also trim the messages key in the database to contain at most the last 21 messages using the ltrim(‘key’,startingIndex,endingIndex) method and we send the newly created message to all connected clients by broadcasting the event with io.sockets.emit(‘eventName’, valueToPass).

 

1

2

3

4

5

6

7

8

9

socket.on("message", function (data) {

if (data.length<100 &&socket.nickname&&socket.nickname.length<= 25) {

varmessage = socket.nickname+ ": " + entities.encode(data)   ;

client.lpush("messages", message);

client.ltrim("messages", 0, 20);

io.sockets.emit("incomingMessage", message);

    }

 

    });

 

Part 1: How to Create Real-time Chat Application with Node.js Part 1

Part 2: How to Create Real-time Chat Application with Node.js Part 2

Part 4: How to Create Real-time Chat Application with Node.js Part 4

 

 

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.bizfacebooktwitter

Article source: https://www.phpgang.com/how-to-create-real-time-chat-application-with-node-js-part-3_2168.html

-->