Today we're going to talk about wehsocket and node development long connection. In a real project, we may want to achieve a function that is not a simple chat function. Now we need to integrate it. Redis Rabbit MQ, etc. implements o2o's reminder function:
First, integrate a redis:
We create a chat folder in which we write a package.json file to generate our node class library
At this point, we install the class library by running the node command, npm install{ "name": "zefun", "version": "1.0.0", "description": "", "main": "index.js", "dependencies": { "apn": "^1.5.2", "amqp": "^0.2.4", "co": "^3.0.6", "co-redis": "^1.1.1", "log4js": "^0.6.28", "express": "^4.13.3", "redis": "^0.10.3", "redis-sentinel": "^0.1.3", "socket.io": "^1.3.7" }, "devDependencies": {}, "author": "", "license": "ISC" }
After installation, we will generate a node_modules file, and create a logs folder in the directory of this layer, because we will use a log system for output later, but node only has the right to write files, not the right to output folders.
Create a new redisClient.js as a client connection to redis
Now we can refer to and pass values in the main js
- var PORT = 6379;
- var HOST = '120.25.254.164';
- var redis = require('redis');
- var chatClient = redis.createClient(PORT,HOST);
- var logger = require("./log").logger("redis");
- chatClient.on('error', function(err){
- logger.error(err);
- });
- var chat_sadd = function(key, field) {
- chatClient.sadd(key, field);
- logger.info("redis sadd --> key : " + key + ", field : " + field);
- }
- var chat_srem = function(key, field) {
- chatClient.srem(key, field);
- logger.info("redis srem --> key : " + key + ", field : " + field);
- }
- var chat_smembers = function(key) {
- return chatClient.smembers(key);
- }
- var chat_hset = function(key, userId, sockedId) {
- chatClient.hset(key, userId, sockedId);
- logger.info("redis hset --> key : " + key + ", field : " + userId + ", value :" + sockedId);
- }
- var chat_hget = function(key, userId) {
- return chatClient.hget(key, userId);
- }
- exports.chat_sadd = chat_sadd;
- exports.chat_srem = chat_srem;
- exports.chat_smembers = chat_smembers;
- exports.chat_hset = chat_hset;
- exports.chat_hget = chat_hget;
We saw above that we used a class library called co and wrapper to wrap redis. Only after wrapping can we handle the asynchronous program in node when we operate redis. We can change redis value into synchronous way, that is, after getting the value, we can execute the following program.
- var co = require('co');
- var wrapper = require('co-redis');
- var redis = wrapper(require("./redisClient"));
There is no need for such synchronization for stored values
- co(function* () {
- <span style="white-space:pre"> </span>var userSID = yield redis.chat_hget(USER_SOCKET_KEY, toUser);
- io.sockets.connected[userSID].emit('getMessage',{msg:msg});
- })();
Even if redis is over, let's start the construction and operation of rabbitMQ.
- redis.chat_sadd(redis_key,data.userId);
Here we use node as a client of rabbit to listen and process. First, we create a new mqClient.js to listen as the client of the queue.
This is the core of our monitoring program, is to subscribe this method, you can listen, please note receiveLogout this method, we need to pass in as parameters in the main js, when the client to pass in a method as an alternative method, you can read the message, but if not, then the data is lost. Here is the main J. The code in S
- conn.queue('queue_chat_notify', { autoDelete: false, durable: true }, function(queue) {
- queue.subscribe(function (msg) {
- receiveNotify(msg.data);
- });
- });
- exports.createConnection = function(r1, r2) {
- receiveLogout = r1;
- receiveNotify = r2;
- }
In this way, after deciding the login in the client, the message in the queue can be read and sent by using this method. The whole content of mqClient.js is given below.
- var mq = require("./mqClient");
- mq.createConnection(receiveNotify);
- //The callback operation of rabbitmq to monitor the notification
- var receiveNotify = function(msg) {
- logger.info("\r\n\r\n<-- receiveNotify begin -->");
- sendMsg(msg);
- }
- var amqp = require("amqp");
- var exchName = "directExchange";
- var connOptions = {
- host: '120.25.254.164',
- port: 5672,
- login: 'zefun',
- password: 'zefun'
- };
- var exchOption = {
- type: 'direct',
- durable: true,
- autoDelete: false,
- confirm: false
- };
- var conn;
- var receiveNotify = null;
- var logger = require('./log').logger("rabbitmq");
- conn = amqp.createConnection(connOptions);
- conn.on('ready',function() {
- logger.info("rabbitmq is ready ... ");
- conn.queue('queue_chat_notify', { autoDelete: false, durable: true }, function(queue) {
- queue.subscribe(function (msg) {
- logger.info("queue_chat_notify consumer msg : " + msg);
- receiveNotify(msg.data);
- });
- });
- });
- conn.on('close', function(){
- logger.error("rabbitmq is close");
- });
- conn.on('error', function (error) {
- logger.error('Connection error : ' + error);
- });
- exports.createConnection = function(r1) {
- logger.info("createConnection r1 : " + r1);
- receiveNotify = r1;
- }
- exports.publish = function(routeKey, message) {
- conn.publish(routeKey, message);
- };
Here's our final step. Let's take a look at what's in servier.js.
- var app = require('express')();
- var http = require('http').Server(app);
- var io = require('socket.io')(http);
- app.get('/', function(req, res){
- res.send('<h1>Welcome Realtime Server</h1>');
- });
- http.listen(3000, function(){
- console.log('listening on *:3000');
- });
- var mq = require("./mqClient");
- var co = require('co');
- var wrapper = require('co-redis');
- var redis = require("./redisClient");
- var redisClient = wrapper(redis.chatClient);
- var logger = require("./log").logger("server");
- var STORE_USER_KEY = "store_to_chat_user_set_";
- var USER_SOCKET_KEY = "chat_user_to_socket_hash";
- //The callback operation of rabbitmq to monitor the notification
- var receiveNotify = function(msg) {
- logger.info("\r\n\r\n<-- receiveNotify begin -->");
- sendMsg(msg);
- }
- mq.createConnection(receiveNotify);
- io.on('connection', function (socket) {
- io.sockets.emit('connect',{hello:'connection success'});
- socket.on('sendMsg', function (from,toUser,msg,msgType) {
- co(function* () {
- var userSID = yield redisClient.hget(USER_SOCKET_KEY, toUser);
- io.sockets.connected[userSID].emit('getMessage',{msg:msg});
- })();
- });
- socket.on('initUser',function(data){
- var redis_key = STORE_USER_KEY + data.storeId;
- //redis insert data
- redisClient.sadd(redis_key,data.userId);
- redisClient.hset(USER_SOCKET_KEY, data.userId, socket.id);
- logger.info('initUser --->> store :' + data.storeId + ', user : ' + data.userId);
- });
- socket.on('disconnect', function () {
- });
- });
- var sendMsg = function(obj){
- co(function* () {
- var socketId = yield redisClient.hget(USER_SOCKET_KEY, obj.toUser);
- logger.info("socketId : " + socketId);
- io.sockets.connected[socketId].emit("getMessage", obj);
- })();
- }
Next, we write a client, which is actually a jsp file.
You can trigger the login and receive the message.
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%
- String chatPath = request.getContextPath();
- String chatPasePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
- + chatPath + "/";
- %>
- <script src="<%=chatPath%>/js/common/socket.io.js"></script>
- <script type="text/javascript">
- var userId = '${session_key_user_id}';
- var storeId = '${session_key_store_id}';
- var user = {"userId" : userId, "storeId" : storeId};
- if(!isEmpty(userId)){
- var socket = io.connect('ws://localhost:3000');
- socket.on('connect', function(data) {
- //Log in to the chat room.
- socket.emit('initUser', user);
- //Receive messages
- socket.on('getMessage', function(data) {
- console.log("" + data);
- var fid = data.fid;
- //PC Notification Class Processing
- if (fid == 2) {
- var type = data.data.type;
- //New appointment
- if (type == 2) {
- //Play voice.
- textToVoice(0, data.data.msg);
- }
- }
- });
- });
- }
- </script>
Remember in Linux Up to boot time Start with a command that acts as a daemon so that the node does not go down as the terminal closes...
At this point, our whole set is finished. Finally, note the log. If we want to import the class libraries into package.json, we can use npm init in the folder to generate JSON files automatically and transplant them.
Give a download link address for the project http://download.csdn .NET/detail/u014201191/9303347
# Special attention should be paid to:
In this case, neither io.sockets.connected[socket.id].emit("method",msg) nor io.sockets.sockets[socket.id].emit("method",msg) is available. Instead, io.to[socket.id].emit("method",msg) triggers the transmission event, as if TM is due to version problems.