layim的websocket消息撤回功能实现

我的大概思路就是,前端根据选取的内容获得他的cid,我的cid是js生成的uuid,
然后:1、通过websocket广播给对应的人 去删除localstorage里的缓存,
2、ajax异步请求删除数据库里的数据记录
3、如果对方此时也打开了聊天面板就要用jquery找到那条消息然后remove。

由于目前发现layim3.6版本并没有给自己发的消息赋值data-cid,所以实现起来比较麻烦。
首先如果你的layim和我一样嵌入到很多页面使用的话,你需要找到一个公共的head.jsp或者menu.jsp去存放uuid的值。如下

<input type="hidden" value="" id="uuid">

然后修改layim.js源码如下
在末尾加入一个生成uuid的函数

1 , guid=function() { 2 var s = []; 3 var hexDigits = "0123456789abcdef"; 4 for (var i = 0; i < 36; i++) { 5 s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); 6 } 7 s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010 8 s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01 9 s[8] = s[13] = s[18] = s[23] = "-"; 10 var uuid = s.join(""); 11 return uuid; 12 } 13 ;

修改发送消息的部分代码如下

1 //发送消息 2 var sendMessage = function(){ 3 var uuid=guid(); 4 $("#uuid").val(uuid); 5 var data = { 6 username: cache.mine ? cache.mine.username : '访客' 7 ,avatar: cache.mine ? cache.mine.avatar : (layui.cache.dir+'css/pc/layim/skin/logo.jpg') 8 ,id: cache.mine ? cache.mine.id : null 9 ,cid: $("#uuid").val() 10 ,mine: true 11 };

实现撤回消息的核心代码如下

1$("body").on("mousedown",".layim-chat-mine>.layim-chat-text",function(e){ 2 if(e.which == 3){ 3 var cid =$(e.target).parent().data("cid")==undefined?$(e.target).parent().parent().data("cid"):$(e.target).parent().data("cid"); 4 var msgDom=$(".layim-chat-mine[data-cid='"+cid+"']") 5 var time= msgDom.find("i").html(); //消息发布时间字符串 6 var now=new Date(); //当前时间 7 var msgTime = new Date(Date.parse(time.replace(/-/g,"/"))); //消息发布时间转换成Date格式 8 console.log(now+"---"+msgTime); 9 if((now - msgTime)/60000 < 2){ //只能撤回2分钟内的消息 10 layer.confirm('确定要撤回消息吗?', {icon: 3, title:'提示'}, function(index){ 11 //console.log(cid); 12 // var windowName=msgDom.find(".layim-chat-other>img").attr("class"); 13 var windowName =$(e.target).parent().parent().parent().find(".layim-chat-other>img").attr("class")==undefined?$(e.target).parent().parent().parent().parent().find(".layim-chat-other>img").attr("class"):$(e.target).parent().parent().parent().find(".layim-chat-other>img").attr("class"); 14 //console.log(windowName); 15 var arr=windowName.split(" "); 16 var localIndex = arr[0].substring(6,windowName.length); 17 //console.log(localIndex); 18 var cache = layui.layim.cache(); 19 var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据 20 //console.log(JSON.stringify(local)); 21 var s=local.chatlog[localIndex]; 22 //console.log(JSON.stringify(s)); 23 var type=s[0].type; 24 var toId=s[0].id; 25 $.post("api/friend/delMsgFromMongoByCid",{"cid":cid,"type":type},function(res){ 26 console.log(res); 27 }) 28 console.log(type); 29 var array=[]; 30 $.each(s,function(k,v){ 31 if(v.cid!=cid){ 32 array.push(v); 33 } 34 }); 35 local.chatlog[localIndex]=array; 36 //向localStorage同步数据 37 layui.data('layim', { 38 key: cache.mine.id 39 ,value: local 40 }); 41 //console.log(local.chatlog[localIndex]) 42 if(type=='friend'){ 43 var obj={ 44 "mine":{ 45 "id":userId 46 }, 47 "to":{ 48 "type":"delMsg", 49 "cid":cid, 50 "id":toId, 51 "toType":type 52 } 53 }; 54 ws.send(JSON.stringify(obj)); 55 }else{ 56 $.post("api/qun/getSimpleMemberByGroupId?groupId="+toId,function(res){ 57 console.log(res); 58 if(res!=null){ 59 var obj1={ 60 "mine":{ 61 "id":userId 62 }, 63 "to":{ 64 "type":"delMsg", 65 "cid":cid, 66 "id":toId, 67 "toType":type, 68 "memberList":res 69 } 70 } 71 ws.send(JSON.stringify(obj1)); //发送消息倒Socket服务 72 } 73 }) 74 } 75 $(e.target).parent().remove(); 76 layer.close(index); 77 }); 78 }else{ 79 layer.msg("超过2分钟的消息无法撤回!",{time:1000}); 80 } 81 } 82 });

禁用浏览器默认右键菜单

1document.oncontextmenu=function(ev){ 2 return false; //屏蔽右键菜单 3}

接收撤销的websocket消息的代码如下

1 ws.onmessage = function (event) { //如果获取到消息,心跳检测重置 2 heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的 3 console.log("llws收到消息啦:" +event.data); 4 if(event.data!='pong'){ 5 var obj=eval("("+event.data+")"); 6 layui.use(['layim'], function(layim){ 7 if(obj.type=="onlineStatus"){ 8 layim.setFriendStatus(obj.id, obj.content); 9 }else if(obj.type=="friend" || obj.type=="group"){ 10 layim.getMessage(obj); 11 }else if(obj.type=="delMsg"){ 12 var cid =obj.cid; 13 var type=obj.toType; 14 var toId=obj.toId; 15 var uId=obj.userId; 16 //console.log(cid); 17 $(".layim-chat-main li[data-cid='"+cid+"']").remove(); 18 var cache = layui.layim.cache(); 19 var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据 20 //console.log(JSON.stringify(local)); 21 var localIndex=""; 22 if(type=='friend'){ 23 localIndex=type+uId; 24 }else{ 25 localIndex=type+toId; 26 } 27 //console.log(localIndex); 28 var s=local.chatlog[localIndex]; 29 //console.log(JSON.stringify(s)); 30 var array=[]; 31 $.each(s,function(k,v){ 32 if(v.cid!=cid){ 33 array.push(v); 34 } 35 }); 36 local.chatlog[localIndex]=array; 37 //向localStorage同步数据 38 layui.data('layim', { 39 key: cache.mine.id 40 ,value: local 41 }); 42 43 } 44 }); 45 } 46 };

java服务端代码如下

1if(type.equals("delMsg")){ 2 String toType=jsonObject.getJSONObject("to").getString("toType"); 3 String toId=jsonObject.getJSONObject("to").getString("id"); 4 String cid=jsonObject.getJSONObject("to").getString("cid"); 5 String userId=jsonObject.getJSONObject("mine").getString("id"); 6 JSONObject toMessage=new JSONObject(); 7 toMessage.put("cid",cid); 8 toMessage.put("userId",userId); 9 toMessage.put("toType",toType); 10 toMessage.put("toId",toId); 11 toMessage.put("type","delMsg"); 12 if(toType!=null && toId!=null && cid!=null){ 13 switch (toType) { 14 case "friend": //单聊撤回 15 if(mapUS.containsKey(toId+"")){ //如果在线,及时推送撤回消息 16 mapUS.get(toId+"").getAsyncRemote().sendText(toMessage.toString()); //发送消息给对方 17 System.out.println("撤回单聊-来自客户端的消息:" + toMessage.toString()); 18 }/*else{ //如果不在线 就直接把redis里的那条记录干掉 // 如果是离线用户,删除保存到redis的数据 List<Object> redisLogList = RedisUtils.getObjList(toId+"_msg"); for (int i=0;i<redisLogList.size();i++){ Object o = redisLogList.get(i); String s = o.toString(); if (s.indexOf(cid) > -1){ RedisUtils.removeOneOfList(toId+"_msg", o); break; } } }*/ 19 break; 20 case "fankui": //家长与老师反馈消息撤回 21 if(mapUS.containsKey(toId+"")){ //如果在线,及时推送撤回消息 22 mapUS.get(toId+"").getAsyncRemote().sendText(toMessage.toString()); //发送消息给对方 23 System.out.println("撤回反馈-来自客户端的消息:" + toMessage.toString()); 24 }/*else{ // 如果是离线用户,删除保存到redis的数据 List<Object> redisLogList = RedisUtils.getObjList(toId+"_msg"); for (Object o : redisLogList){ String s = o.toString(); if (s.indexOf(cid) > -1){ RedisUtils.removeOneOfList(toId+"_msg", o); break; } } }*/ 25 break; 26 case "group": 27 //JSONArray memberList=JSONArray.fromObject(llClient.getGroupUser(Integer.parseInt(toId))); //获取群成员userId列表 28 JSONArray memberList=jsonObject.getJSONObject("to").getJSONArray("memberList"); 29 if(memberList.size()>0){ 30 for(int i=0;i<memberList.size();i++){ //发送到在线用户(除了发送者) 31 if(mapUS.containsKey(memberList.get(i)) && !memberList.get(i).equals(jsonObject.getJSONObject("mine").getInt("id")+"")){ 32 session=mapUS.get(memberList.get(i)); 33 session.getAsyncRemote().sendText(toMessage.toString()); 34 System.out.println("撤回群聊-来自客户端的消息:" + toMessage.toString()); 35 }/*else if(memberList.get(i).equals(jsonObject.getJSONObject("mine").getInt("id")+"")){ //如果是发送者自己,不做任何操作。 }else{ //如果是离线用户,数据存到redis待用户上线后推送。 List<Object> redisLogList = RedisUtils.getObjList(memberList.get(i) + "_msg"); for (Object o : redisLogList){ String s = o.toString(); if (s.indexOf(cid) > -1){ RedisUtils.removeOneOfList(memberList.get(i) + "_msg", o); break; } } }*/ 36 } 37 } 38 break; 39 default: 40 break; 41 } 42 }

分享完毕,有问题可以联系qq:1434262447,加我时备注一下

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java将前端的json数组字符串转换为列表

记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )