实现不同聊天对话的动态切换
让不同聊天窗口展示自己的消息,而不展示别人的消息
点击不同的聊天对象,把消息展示出来。
首先保存当前记录,有人点击就展示出来
function Session_hpy(contact_id,contact_type,action){
if (action == 'dump'){
//保存当前聊天记录
var current_dialog_content = $(".dialog-box-content").html();
all_dialog_sessions[contact_type][contact_id] = current_dialog_content;
}
else if(action =='load'){
//把指定的contact id的聊天记录加载出来
var new_dialog_content = '';
if (all_dialog_sessions[contact_type].hasOwnProperty(contact_id)){
new_dialog_content = all_dialog_sessions[contact_type][contact_id]
}
return new_dialog_content;
}
}
实现无延迟实时聊天
用请求类(utils.py 的Chat类)下面的get_msg实现实时聊天
def get_msg(request):
uid = request.GET.get('uid')
if uid:
#判断是否有消息
res = []
if uid not in global_msg_dic:
global_msg_dic[uid] = utils.Chat()
#调用类下面的get_msg方法
res = global_msg_dic[uid].get_msg(request)
return HttpResponse(json.dumps(res))
else:
return HttpResponse(json.dumps("uid not provided!"))
好了,到这里就实现完了。整个过程记录的有点粗糙。
效果展示图:
打开两个不同的浏览器(IE除外),分别用用户hpy和hx登录。
现在hx向hpy发送3条消息:
由于hpy当前没有和hx聊天,所有就会出现提示收到了hx发来的三条消息
hpy点击联系人hx去读取消息,消息便会被展示出来:
最后完成实时聊天,hpy向hx发送消息:
由于hx正在和hpy聊天变会立刻出现消息:
后端的数据接收和转发:
有消息就push,
没有就等待6秒