Implementing basic chat room scenarios with node. js + Socket.io + Redis

Source: Internet
Author: User
Tags emit

The basic operations of Redis and REDIS-CLI are described in this article in the Redis database and its basic operations. The publish-subscribe mechanism is widely used, then the NODEJS is used to implement the mechanism. This article is a detailed supplement to the basic chat room scenario using Socket.io+redis for a previous article.
For more information about Redis, refer to the Redis database and its basic operations.
The prerequisite for Redis is that Redis-server is always running, and the default localhost:6379 is used here.

node. js Connection Redis-server

Install the Redis module, which is installed by default into the Node_modules in the current directory:

install redis

Then connect to Redis and perform get-set operations

varrequire(‘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:

require(‘redis‘sub = function(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 launched to compare and execute the results:

node. JS launches a Httpserver
varrequire(‘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/‘);

Execution can see:

Socket.io synchronizing data in browser with server

The Socket.io is connected between the HTTP servers of browser and Nodejs and can be used to synchronize data between them.
Server side: Start Httpserver listening on port 4000, once a socket.io connection is established, send a msgreceived message to the socket, and the message content is ' hello '.

var Server =require(' http '). Createserver ( function (request, response) {Response.writehead ( $, {' Content-type ':' Text/plain '}); Response.End(' Hello world\n ');}). Listen4000); Console.log (' Server running at Http://127.0.0.1:4000/'); vario=require(' Socket.io ') (server);io. On (' Connection ', function(socket) {Console.log (' Connection '); Socket.emit (' msgreceived ',' Hello ');})

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

<html><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:4000 '); Socket.on (' connection ',  function() { console.log (' connection setup for sock    Et.io ')});    Socket.on (' msgreceived ',  function(msg) { alert (msg); })</script></html>

To make it easier to see better results, turn on all two browser, and when Httpserver does not start, only the Hello World is displayed in browser. Once you start Httpserver:node testserver.js, you can see that two browser will automatically pop up alert, indicating that a message was received from the Socket.io. Execution results such as:

Then, stop httpserver, change the content of the sending msgreceived message to ' world ', and two browser again pop up the corresponding alert. Such as:

This indicates that the data can be synchronized between Httpserver and browser by Socket.io connection. This is where httpserver the Hello and the world to browser, respectively.

Show the results of subscribe in browser

The next thing to do is to subscribe to Redis's Chatchannel channel via Httpserver and update the channel's content to browser.
The browser end is unchanged, and the server side changes to:

varServer =require(' http '). Createserver ( function (request, Response) {Response.writehead ( $, {' Content-type ':' Text/plain '}); Response.End (' Hello world\n ');}). Listen4000);varRedis =require(' Redis ');varRedisclient = Redis.createclient ();varSub = function(c) {    varc = C | |' Chatchannel '; Redisclient.subscribe (c, function(e) {Console.log (' Subscribe channel: '+ c); });} Sub (); Console.log (' Server running at Http://127.0.0.1:4000/');varIO =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 Subscribe to the Redis-server Chatchannel Channel, when the Socket.io connection is established, listen to the redisclient message, once received the Chatchannel channel to publish the message, Send msgreceived messages to all connected browser immediately via Socket.io, which is the content of the Chatchannel channel. We are here to use REDIS-CLI to publish messages, and of course we can use other methods.
The results of the implementation are as follows:
First, Redis-cli didn't publish the message.

Then, publish the message ' How is you ' and two browser will receive:

Finally, the release message ' Thank you, goodbye ', two browser will receive:

At this point, using node. js and Socket.io, combined with the publish-subscribe mechanism of Redis, the implementation of the chat room scene is basically feasible.

Implementing basic chat room scenarios with node. js + Socket.io + Redis

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.