我想创建聊天记录的二维数组,其中第一个数组表示userid,嵌套数组表示用户相关的聊天记录。但我找不到如何在subscriber.hget()函数中插入数组“arrChatMembersLog”。当我获取数组值时它总是为空,否则如果我试图在函数“callBackSubscriberHGETMessageTable()”中打印数组,其中subscriber.hget()调用它显示2d数组,除了正在运行循环的消息之外全部为空。你可以提供任何解决方案,我应该填写arrChatMembersLog数组()中的所有聊天记录。
方法信息::
get_old_data():
这是执行开始的主要方法。用户通过点击他/她的名字与所需的朋友聊天。点击它显示聊天窗口并发送非常时间的消息。当消息发送时,它会获取它们之间的所有过去的对话。它获取在redis中创建的所有通道。
callBackSubscriberHGetAll():
它获取消息所有消息更改并将所有消息ID存储在一个数组中。使用该数组我从哈希中获取消息。
callBackSubscriberHGETMessageTable():
它通过调用callBackSubscriberHGetAll()函数获取基于数组创建的所有消息。这里出现了实际问题。我想将所有消息数据存储在arrChatMembersLog数组中。但由于nodejs的异步性质,我无法在arrChatMembersLog中保存所有数组值。
所需的数组格式
第一个索引表示Userids,第二个索引是该用户的聊天记录。
arr[1][0] = {},
arr[1][1] = {},
arr[1][2] = {},
arr[2][0] = {},
arr[2][1] = {},
arr[2][2] = {},
arr[3][0] = {},
arr[3][1] = {},
arr[3][2] = {},
server.js
/*
* -------------------
* Express
*
* -------------------
*/
var app = require('express')(),
http = require("http"),
url = require('url'),
cookieParser = require('cookie-parser'), // the session is stored in a cookie, so we use this to parse it
session = require('nodePhpSessions').SessionHandler,
sessionHandler = new session(),
morgan = require("morgan"),
expressSession = require("express-session"),
phpUnserialize = require("php-unserialize"),
sessionStore = new expressSession.MemoryStore(),
parseUrl = null, uId = null, uName = null, uEmail = null;
// Transaction logger
app.use(morgan("dev"));
// must use cookieParser before expressxSession
app.use(cookieParser());
app.use(expressSession({
name: "Whizchat",
secret: '47760ae7-9660-4d4c-b15d-b9986edccbf3ss',
store: sessionStore,
saveUninitialized: true,
resave: true,
cookie: {
path: "/",
httpOnly: true,
secure: true,
maxAge: null,
}
}));
//app.set(app.session({secret: 'secret', key: 'express.sid'}));
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
next();
});
app.set('host', "localhost");
//var port = normalizePort(process.env.PORT || '3000');
//app.set('port', port);
app.set('port', "3000"); //process.env.PORT
/*
* -------------------
* Socket Connections
* -------------------
*/
//var server = require('http').createServer(app);
var server = http.createServer(function (req, res) {
parseUrl = url.parse(req.url, true).query;
if ("string" === typeof (parseUrl.dataJSON)) {
var _objUser = JSON.parse(parseUrl.dataJSON);
uId = (_objUser.user_id === undefined || _objUser.user_id === "" || _objUser.user_id === null) ? null : _objUser.user_id;
uName = (_objUser.username === undefined || _objUser.username === "" || _objUser.username === null) ? null : _objUser.username;
uEmail = (_objUser.user_email === undefined || _objUser.user_email === "" || _objUser.user_email === null) ? null : _objUser.user_email;
}
res.writeHead(200, {'Content-type': "text/plain"});
res.end(sessionHandler.run(parseUrl));
});
var io = require('socket.io')(server);
server.listen(app.get("port"), app.get("host"), function () {
console.log("Server up and running...");
});
server.on('error', function (e) {
console.log("Error occured :" + e);
});
//io.set('log level', 3);
/*
* -------------------
* Redis
* -------------------
*/
var redis = require("redis");
/*
* Sender
*/
var publisher = redis.createClient();
/*
* Receiver
*/
var subscriber = redis.createClient();
/*
* Message counter
*/
//var messageLen = llen messages;
/*
* List of all channels (sorted set using Z<command>)
* Sorted set name : channels
*/
var channel_Count = 0;
var channel_name = "channel";
var user_channel = 0
/*
* Lists of all users (sorted set using Z<command)
* Sorted set name : onlineusers
*/
var userlists = [], usersSocket = [];
var uids = [], socketids = [];
var get_old_communication_channel_name = "";
/*
* All Users related channels set ( unordered/unsorted set using s<command>)
* Unsorted set name : userschannel
*/
var usersChannels;
var msgChannel = "messageChannelSet";
var messageTable = "messageTable";
/*
* Message set (sorted set)
*/
var message_Id = 1;
//global array
var arr_msg_id = [];
var arr_sender_reciver_msg = [];
var employees = [];
var arr1 = [];
var arr11 = [];
/*
* User set
*/
var channelSet;
var countMember, countChannel;
var arrChatMembersLog = [];
/*
* Identified that user_reference_id based set (unordered) is generated or not
*/
/*foreach userSet on <user>
var countMember = smembers <user>;
if(countMember is empty set or nil){
isNewChannelGenerate = true;
}
endforeach
*/
/*
* -------------------
* Mysql
* -------------------
*/
/*var mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "whiz"
});
connection.connect();*/
/*
* -------------------
* functions
* -------------------
*/
function subscribeMessage(_subscriber) {
subscriber.subscribe(_subscriber);
subscriber.on("message", function (channel, message) {
console.log("redis connection message:" + message);
});
}
function createNewChannel(){
//return true;
}
function showArray(){
console.log("My data:");
console.log(" =============================== ");
console.log(arrChatMembersLog);
console.log(" =============================== ");
}
function insertDataInArray(index, loopindex, replies2){
arrChatMembersLog[index][loopindex] = JSON.stringify(replies2);
}
function callBackSubscriberHGETMessageTable(messagesIds, index){
console.log("messages index of i "+ index + "::" + messagesIds.length);
console.log("message data:"+messagesIds);
arrChatMembersLog[index] = new Array(parseInt(messagesIds.length));
for (var j in messagesIds) {
var _index = messagesIds[j];
var loopindex = 0;
subscriber.HGET(messageTable, _index, function(err, replies2) {
//console.log("array index :"+index+":data "+j+":Ids "+_index+":Loopindex "+loopindex+" === "+replies2);
//arrChatMembersLog[index][loopindex] = JSON.stringify(replies2);
insertDataInArray(index, loopindex, replies2);
console.log(arrChatMembersLog);
loopindex++;
});
}
}
function callBackSubscriberHGetAll(i){
subscriber.HGETALL("message_channel"+i, function(err, replies1) {
var k=1;
for (k in replies1) {
arr_msg_id.push(JSON.parse(replies1[k]));
}
callBackSubscriberHGETMessageTable(arr_msg_id, i);
arr_msg_id.splice(0,arr_msg_id.length);
});
}
function get_old_data(){
/*
* Grep total channels created in redis database of all users.
*/
subscriber.SCARD(msgChannel, function(err, channel_Count) {
var i=1, j=1;
console.log("channel count :"+channel_Count);
for(i =1; i<=channel_Count; i++){
callBackSubscriberHGetAll(i);
}
});
}
function setMessageData(msg){
console.log("message call");
arr_sender_reciver_msg.push(JSON.stringify(msg));
}
function pushToRedis(subscriber, data) {
console.log("push to channel"+JSON.stringify(data));
console.log(" call first push ..."+data.uId+"==="+data.reciver);
var msg = data.msg;
var channel_name;
if(data.uId && data.reciver){
subscriber.SINTER("user_"+data.uId, "user_"+data.reciver, function(err, replies) {
console.log("get_old_communication_channel_name :"+get_old_communication_channel_name+"=="+replies);
if(get_old_communication_channel_name != replies) {
arr_msg_id.splice(0,arr_msg_id.length);
arr_sender_reciver_msg.splice(0,arr_sender_reciver_msg.length);
}
get_old_communication_channel_name = replies;
//one to one communication in message new create channels replies == 0 then
console.log("replies SCARD :"+replies.length);
if(replies.length == 0){
var channel_Count_no;
subscriber.SCARD(msgChannel, function(err, channel_Count) {
console.log("channel_Count :"+channel_Count);
if(channel_Count == 0){
channel_name = "channel1";
subscriber.SADD("user_"+data.uId, "channel1");
subscriber.SADD("user_"+data.reciver, "channel1");
subscriber.SADD("channelSet", "channel1");
}else{
channel_Count_no = channel_Count + 1;
channel_name = "channel"+channel_Count_no;
subscriber.SADD("user_"+data.uId, "channel"+channel_Count_no);
subscriber.SADD("user_"+data.reciver, "channel"+channel_Count_no);
subscriber.SADD("channelSet", "channel"+channel_Count_no);
// subscriber.SADD(msgChannel, "message_channel"+channel_Count_no);
}
});
}
console.log(" call first push1 ...");
//one to one communication in message new create channels replies == 1 then
if(replies.length == 1){
get_old_communication_channel_name = replies;
channel_name = replies;
console.log("ch_name :"+replies);
console.log("data.msg :"+msg);
console.log("msgChannel :"+msgChannel);
console.log("arr_msg_id.length :"+arr_msg_id.length);
if(arr_msg_id.length < 1 ){
console.log("arr_msg_id.length After :"+arr_msg_id.length);
subscriber.HGETALL("message_"+channel_name, function(err, replies1) {
/*
* HGETALL redis command to get all redord and for lop to javascript insert in this arr_msg_id array.
* After for loop to get all record in messageTable.
*/
console.log("replies1 :" +replies1.length);
for (i in replies1) {
arr_msg_id.push(JSON.parse(replies1[i]));
}
console.log(arr_msg_id.length);
for (i in arr_msg_id) {
var _index = arr_msg_id[i];
subscriber.HGET(messageTable, _index, function(err, replies2) {
arr_sender_reciver_msg.push(JSON.parse(replies2));
//setMessageData(replies2);
});
}
console.log("isert arr_sender_reciver_msg cumplited...");
});
}
console.log(" call first push2 ...");
/*
* First time Add new messageChannelSet in message_channel1,2,3...
* Not insert message_channel1,2,3... duplicate
*/
}
subscriber.HLEN(messageTable, function(err, replies1) {
subscriber.SADD(msgChannel, "message_"+channel_name);
message_Id = replies1 + 1;
subscriber.HSET(messageTable, message_Id, JSON.stringify(data), function(err, reply) {
if (err) throw err;
console.log("Reply : "+ reply);
});
//subscriber.HSET(messageTable, message_Id, "sender:'"+data.uId+"', reciver:'"+data.reciver+"', meg:'"+data.msg+"', time:'"+data.date+"'");
/*
* message_channel1,2,3....
* that match message_channel in insert ID and massage_text.
*/
subscriber.HSET("message_"+channel_name, "msg_"+message_Id, message_Id);
//arr_sender_reciver_msg.push({uId : data.uId,from : data.from,msg : data.msg, reciver : data.reciver,})
});
console.log(" call first push3 ...");
//pushTOmessage(subscriber, data);
});
}
}
function getCurrentTime() {
return Math.floor(new Date().valueOf() / 1000);
}
function accessSecureSessionInfo() {
//console.log("type:" + typeof (parseUrl.dataJSON));
if ("string" === typeof (parseUrl.dataJSON)) {
console.log("step in 1");
var _objUser = JSON.parse(parseUrl.dataJSON);
// console.log("usrname;" + _objUser.username);
uId = (_objUser.user_id === undefined || _objUser.user_id === "" || _objUser.user_id === null) ? null : _objUser.user_id;
uName = (_objUser.username === undefined || _objUser.username === "" || _objUser.username === null) ? null : _objUser.username;
uEmail = (_objUser.user_email === undefined || _objUser.user_email === "" || _objUser.user_email === null) ? null : _objUser.user_email;
}
}
/*
* -------------------
* Redis Subscriber
* -------------------
*/
if (uId && uName && uEmail) {
subscriber.subscribe("whizchannel");
subscribeMessage("whizchannel");
}
var basket = {};
var index =0;
io.sockets.on('connection', function (socket) {
var _subscriber = redis.createClient();
socket.on('connection', function (cma) {
console.log('Server running on *:' + app.get('port'));
});
console.log("index:"+index++);
socket.on("join",function(data){
console.log("before start:"+userlists.length);
console.log("datauid:"+data.uid);
if(data.uid !== null && data.uid !== undefined && data.uid !== "") {
//console.log("after start:"+userlists.length);
//console.log("Join called for :"+data.uid);
//console.log("socketid:"+socket.id);
//console.log("datuid:"+data.uid);
var _socketid = socket.id;
var _uid = data.uid;
var _findIndex = uids.indexOf(_uid)
if(_findIndex === -1){
uids.push(_uid);
socketids.push(_socketid);
}else if(_findIndex !== -1){
socketids[_findIndex] = _socketid;
}
io.sockets.sockets[_uid] = _socketid;
//userlists[_uid]=_socketid;
//console.log("user array");
//console.log(userlists);
//console.log("users length:"+users.length);
//console.log("userssocket length:"+usersSocket.length);
}
});
console.log("Userslists:"+userlists);
socket.on("chat1", function (data) {
console.log("frist call chat 1......");
var _data = {
uId : data.sender_id,
from: data.sender_name,
msg: data.msg,
reciver : data.reciver,
//date: getCurrentTime()
};
get_old_data();
// pushToRedis(_subscriber, _data);
});
socket.on("chat", function (data) {
console.log("After call chat emited......");
var dt = new Date();
var hours = dt.getHours();
var mid;
if(hours >= 12){ mid='pm';}
else{ mid='am';}
var time = (dt.getHours() < 10?'0':'')+dt.getHours()+ ":" + (dt.getMinutes() < 10?'0':'')+dt.getMinutes() + ":" + (dt.getSeconds() < 10?'0':'')+dt.getSeconds()+" "+mid;
var _data = {
uId : data.sender_id,
from: data.sender_name,
msg: data.msg,
reciver : data.reciver,
//date: time
//date: getCurrentTime()
};
//basket[data.replies] = socket.id;
// io.sockets.socket(to).emit(data.msg);
console.log("------------------------------------\n");
console.log(employees);
console.log("------------------------------------\n");
console.log("call pushToredish function");
arr_sender_reciver_msg.push({uId : data.sender_id,from : data.sender_name,msg : data.msg, reciver : data.reciver})
// io.sockets.socket(_data.reciver).emit(_data.msg);
console.log("users:"+userlists.length);
//socket.emit("publishMessage", arr_sender_reciver_msg);
//console.log("user.sender_id"+users[data.sender_id]);
var _sender_id = data.sender_id;
var _uIndex = uids.indexOf(data.reciver.toString());
console.log(uids);
console.log(socketids);
console.log("senderid:"+_sender_id);
console.log("receiverid:"+data.reciver);
console.log("index:"+_uIndex);
console.log("receiver:"+uids.indexOf(data.reciver.toString()));
if(_uIndex !== -1){
console.log("call to publish ....");
var _socketId = socketids[_uIndex];
}
socket.emit("Current_publishMessage", _data);
//socket.broadcast.emit("Current_publishMessage", _data);
});
// socket.onclose = function () {
// console.info('Socket is now closed.');
// }
socket.on('disconnect', function () {
});
});