Use node. js + socket. io + redis to implement basic chat room scenarios

Source: Internet
Author: User
Tags emit install redis

Use node. js + socket. io + redis to implement basic chat room scenarios

This article introduces the basic operations of Redis and Redis-cli in the redis database and its basic operations. among them, the publish-subscribe mechanism is widely used, so we will use nodejs to implement this mechanism. this article describes how to use socket in the previous article. io + redis to supplement basic chat room application scenarios in detail.
For details about redis, refer to the Redis database and its basic operations.
The premise for redis is that redis-server is always running. The default localhost: 6379 is used here.

Node. js connects to redis-server

Install the redis module, which is installed in the node_modules directory by default:

npm install redis

Connect to redis and perform the get-set operation.

var redis = require('redis');var redisclient = redis.createClient();redisclient.on('connect',function(){  redisclient.set('author', 'testauthor', redis.print);  redisclient.get('author', redis.print);  redisclient.get('hello', redis.print);});

Execution result:

?  socketio  node redis_node.jsReply: OKReply: testauthorReply: world
Node. js implements redis's publish-subscribe

The Code is as follows:

var redis = require('redis');var redisclient = redis.createClient();var sub = function(c) {    var c = c || 'chatchannel';    redisclient.subscribe(c, function(e) {        console.log('subscribe channel : ' + c);    });}sub();redisclient.on('message', function(error, response) {    console.log(response);})

In addition, a redis-cli subscribe is started for comparison. The execution result is as follows:

Node. js starts an httpServer
var http = require('http');// var server = http.createServer().listen(4000);http.createServer(function (request, response) {  response.writeHead(200, {'Content-Type': 'text/plain'});  response.end('Hello World\n');}).listen(4000);console.log('Server running at http://127.0.0.1:4000/');

Run the command to view the following information:

Socket. io synchronizes data between browser and server

Socket. io is connected to the http server of browser and nodejs and can be used to synchronize data between them.
Server: Start httpserver to listen to port 4000. Once a socket. io connection is established, msgReceived messages are sent to the socket, and the message content is 'Hello '.

var server = require('http').createServer(function (request, response) {  response.writeHead(200, {'Content-Type': 'text/plain'});  response.end('Hello World\n');}).listen(4000);console.log('Server running at http://127.0.0.1:4000/');var io = require('socket.io')(server);io.on('connection', function(socket) {    console.log('connection');    socket.emit('msgReceived', 'hello');})

Browser:
Establish a socket connection, then receive the msgReceived message on the socket, and display it.

<Script src = "https://cdn.socket.io/socket.io-1.3.5.js"> </script> hello world <script type = "text/javascript"> console. log ("hello"); var socket = io ('HTTP: // localhost: 100'); socket. on ('connection', function () {console. log ('Connection setup for socket. io ')}); socket. on ('msgreceived', function (msg) {alert (msg) ;}) </script> 

To make it easier to see better results, open both browsers. When httpserver is not started, only hello world is displayed in browser. once you start httpserver: node testserver. js, you can see that both browsers will automatically pop up alert, indicating that the socket is received. messages in io. the execution result is as follows:

Then, stop the httpserver and change the content of the msgReceived message to 'World'. Then, the corresponding alert is displayed in the two browsers again. For example:
Publish + MHLYnJvd3Nlci48L3A + DQo8aDIgaWQ9 "show subscribe results in browser"> display subscribe results in browser

The next step is to subscribe to the redis chatchannel through httpserver and update the content published by this channel to the browser.
The browser side remains unchanged, while the server side changes:

var server = require('http').createServer(function (request, response) {  response.writeHead(200, {'Content-Type': 'text/plain'});  response.end('Hello World\n');}).listen(4000);var redis = require('redis');var redisclient = redis.createClient();var sub = function(c) {    var c = c || 'chatchannel';    redisclient.subscribe(c, function(e) {        console.log('subscribe channel : ' + c);    });}sub();console.log('Server running at http://127.0.0.1:4000/');var io = require('socket.io')(server);io.on('connection', function(socket) {    redisclient.on('message', function(error, msg) {        console.log('connection');        console.log(msg);        socket.emit('msgReceived', msg);            });})

First, redisclient subscribes to the redis-server chatchannel. when an I/O connection is established, the system listens to the redisclient message. Once a message published by the chatchannel channel is received, the system immediately uses the socket. io sends the msgReceived message to all browsers that establish a connection. The message content is published by the chatchannel channel. here, we use redis-cli to publish messages. Of course, we can also use other methods.
The execution result is as follows:
First, the redis-cli does not publish messages.

Then, when the message 'How are you 'is published, both browsers will receive:

Finally, publish the message 'Thank you, goodbye '. Both browsers will receive the following message:

Now, the chat room scenario is basically feasible with node. js and socket. io combined with redis's publish-subscribe mechanism.

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.