Layim 聊天功能

效果图

引用

<link rel="stylesheet" href="static/layim/dist/css/layui.css">
    <script type="text/javascript src="static/layim/dist/layui.all.js"></script>
    <script type="text/javascript src="static/layim/dist/layimindex.js"></script>
    <script src="static/layim/dist/layui.js"></script>
    <script src="static/layim/webchat.js"></script>

前台代码


var $;

if(!/^http(s*):\/\//.test(location.href)){
  alert('请部署到localhost上查看该演示');
}
var layimGb=null;
var uname="";
var sid="";

var host="ws://localhost:8080/xtgsnew/LL_ws/";

var ws;


layui.use('layim', function(layim){
    $ =layui.$;
  layimGb=layim;
  //基础配置
  layim.config({

    //初始化接口
    init: {
      url: 'http://localhost:8080/xtgsnew/CommonUtil/getUserMsg'
      //url: 'json/getList.json'
      ,data: {}
    }
    
   

    //查看群员接口
    ,members: {
      url: 'json/getMembers.json'
      ,data: {}
    }
    
    //上传图片接口
    ,uploadImage: {
      url: '/upload/image' //(返回的数据格式见下文)
      ,type: '' //默认post
    }
    
    //上传文件接口
    ,uploadFile: {
      url: '/upload/file' //(返回的数据格式见下文)
      ,type: '' //默认post
    }
    
    ,isAudio: true //开启聊天工具栏音频
    ,isVideo: true //开启聊天工具栏视频
    
    //扩展工具栏
    ,tool: [{
      alias: 'code'
      ,title: '代码'
      ,icon: '&#xe64e;'
    }]
    
    //,brief: true //是否简约模式(若开启则不显示主面板)
    
    //,title: 'WebIM' //自定义主面板最小化时的标题
    //,right: '100px' //主面板相对浏览器右侧距离
    //,minRight: '90px' //聊天面板最小化时相对浏览器右侧距离
    ,initSkin: '5.jpg' //1-5 设置初始背景
    //,skin: ['aaa.jpg'] //新增皮肤
    //,isfriend: false //是否开启好友
    //,isgroup: false //是否开启群组
    //,min: true //是否始终最小化主面板,默认false
    ,notice: true //是否开启桌面消息提醒,默认false
    //,voice: false //声音提醒,默认开启,声音文件为:default.mp3
    
    ,msgbox: layui.cache.dir + 'css/modules/layim/html/msgbox.html' //消息盒子页面地址,若不开启,剔除该项即可
    ,find: layui.cache.dir + 'css/modules/layim/html/find.html' //发现页面地址,若不开启,剔除该项即可
    ,chatLog: layui.cache.dir + 'css/modules/layim/html/chatlog.html' //聊天记录页面地址,若不开启,剔除该项即可
    
  });

  //监听自定义工具栏点击,以添加代码为例
  layim.on('tool(code)', function(insert){
    layer.prompt({
      title: '插入代码'
      ,formType: 2
      ,shade: 0
    }, function(text, index){
      layer.close(index);
      insert('[pre class=layui-code]' + text + '[/pre]'); //将内容插入到编辑器
    });
  });
 
 
 

        layim.on('ready', function(options){
              console.log(options);
              debugger;
              uname=options.mine.username;
              sid=options.mine.id;
              getHistMsg(layui,uname+"_"+sid);
              //链接聊天
              conWebSocket();
              
            });


  //监听发送消息
  layim.on('sendMessage', function(data){
    debugger;
    var To = data.to;
   
      var obj={
              type:1,
        userName:uname+"_"+sid,
        contentType:"online",
        to:data.to.name+"_"+data.to.id,
        from:data.mine
              }
      var message =JSON.stringify(obj);
      ws.send(message);
 
    
  });

  //监听查看群员
  layim.on('members', function(data){
    //console.log(data);
  });
 
  //监听聊天窗口的切换
  layim.on('chatChange', function(res){
    
  });
});

function getHistMsg(layui,userID){
//获取离线消息
              layui.$.get("http://localhost:8080/xtgsnew/FriendWS/getUnreadMessage?userId="+userID,function(data){
              debugger;
                  for(var i=0;i<data.length;i++)
                  {
                  var from=data[i].friend_message.from;
                       layimGb.getMessage({
                    username: from.username
                    ,type:  "friend"
                ,avatar:from.avatar
                ,id: from.id
                    ,content:from.content
                    ,time:data[i].friend_message.time
                });
                  }
              });
}

function conWebSocket(){
host=host+uname+"_"+sid;
if ('WebSocket' in window) {  
    ws=new WebSocket(host);  
} else if ('MozWebSocket' in window) {  
    ws= new MozWebSocket(host);
} else {
    layui.use(['layer'], function(){
          var layer = layui.layer;
          layer.alert("您的浏览器不支持webscoket协议,建议使用新版谷歌、火狐等浏览器,请勿使用IE10以下浏览器,360浏览器请使用极速模式,不要使用兼容模式!");
    });
}

ws.onopen = function(e) {
    
}
    
ws.onclose = function(e) {
    console.log("ws断开连接!");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。  
window.onbeforeunload = function () {  
      ws.close();  
}  
ws.onmessage = function(e) {

var v=eval("("+e.data+")");

 var from= v.from;
 //chat
  layimGb.getMessage({
    username: from.username
    ,type:  "friend"
    ,avatar: from.avatar
    ,id: from.id
    ,content:from.content
    ,time:v.time
  });
}
    
ws.onerror = function(e) {
    layui.use(['layer'], function(){
          var layer = layui.layer;
          layer.alert("ws发生错误,请勿使用IE9以下浏览器,360浏览器请使用极速模式,不要使用兼容模式!");
    });
}

}

后台代码

package com.nome.plugin.layim;

import static org.hamcrest.CoreMatchers.nullValue;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.sun.org.apache.bcel.internal.generic.NEW;

import net.sf.json.JSONObject;
//userName猜测是个任意字符串
import oracle.net.aso.a;
@ServerEndpoint("/LL_ws/{userName}")
public class LLWebSocket {
    private static int onlineCount = 0;
   // public static Map<String,Session> mapUS=new HashMap<String,Session>();//根据用户找session
   // public static Map<Session,String> mapSU=new HashMap<Session,String>();//根据session找用户
    //ConcurrentHashMap是线程安全的,而HashMap是线程不安全的。
    public static ConcurrentHashMap<String,Session> mapUS = new ConcurrentHashMap<String,Session>(); 
    private static ConcurrentHashMap<Session,String> mapSU = new ConcurrentHashMap<Session,String>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userName") String userName){
     //this.session=session;
     mapUS.put(userName,session);
     mapSU.put(session,userName);
     //上线通知由客户端自主发起
     onlineCount++;           //在线数加1
        System.out.println("用户"+userName+"进入wsll!当前在线人数为" + onlineCount);
       
       
    }
    
    /**
     * 连接关闭调用的方法
     */
 @OnClose
    public void onClose(Session session){
     String userName=mapSU.get(session);
     if(userName!=null&&userName!=""){
         //下线通知
         JSONObject jsonObject=new JSONObject();
         jsonObject.put("type", 3);
         jsonObject.put("userName", userName);
         jsonObject.put("contentType", "offline");
         jsonObject.put("to", "all");
         String jsonString=jsonObject.toString();
         for(Session s:session.getOpenSessions()){//循环发给所有在线的人
       s.getAsyncRemote().sendText(jsonString);
      }
         onlineCount--;           //在线数减1   
            System.out.println("用户"+userName+"退出wsll!当前在线人数为" + onlineCount);
         mapUS.remove(userName);
         mapSU.remove(session);
     }
    }
    /**
     * 收到客户端消息后调用的方法
     */
 static Map offLineDB = new HashMap();
 
 @OnMessage
    public void onMessage(String message,Session session) {
        //System.out.println("来自客户端的消息:" + message);
        JSONObject jsonObject=JSONObject.fromObject(message);
        int type = jsonObject.getInt("type");
        String to=jsonObject.getString("to");
        jsonObject.remove("to");
        //if(type==0||to==null||to==""){return ;}
       
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time=df.format(new Date());// new Date()为获取当前系统时间
        jsonObject.put("time", time);
       
        Session socketoffline_to=mapUS.get(to);
        if(socketoffline_to==null||"".equals(socketoffline_to))
        {
         //离线消息,A给B发的消息格式
         //以下内容来自message这个代码
         //{"type":1,"userName":"贤心_100001","contentType":"online","to":"纸飞机_100000","from":{"username":"贤心","avatar":"http://cdn.firstlinkapp.com/upload/2016_6/1465575923433_33812.jpg","id":"100001","mine":true,"content":"4444444444444444"}}
            //离线表:ID 内容 就是上面那个message   接收人就是 to   状态未读
         //当B进入页面在线的时候,通过ajax获取自己的维度消息表,这时候吧状态改成已读
         //ajax未读消息返回 格式如上寸的那个{"type":1,"userName":"....
         
/*         ("username":鲁涛,内容:123,to:小黄,state:1)
         ("username":鲁涛,内容:456,to:小黄)
         ("username":鲁涛,内容:444,to:小黄)
         
         
         ("username":123,内容:456,to:ZZ黄)
         */
         List offcontentList =null;
         String userName = jsonObject.getString("userName");
         String from = jsonObject.getString("from");
           JSONObject fromObject=JSONObject.fromObject(from);
           String content=fromObject.getString("content");
         offcontentList=(List) offLineDB.get(userName);
         if(offcontentList==null)
         {
          offcontentList=new ArrayList<String>();
          
         }
          offcontentList.add(content);
          
   
         offLineDB.put(userName, offcontentList);
         
         
         return;
        }
       
 
      switch (type) {
  case 1://单聊
   Session session_to=mapUS.get(to);
         if(session_to!=null){
          session_to.getAsyncRemote().sendText(jsonObject.toString());
          //System.out.println("发给"+to+":"+jsonObject.toString());
         }
   break;
  case 2://群聊
   String[] members=to.split(",");
   //发送到在线用户
   for(String member:members){
    session=mapUS.get(member);
    if(session!=null){
     session.getAsyncRemote().sendText(jsonObject.toString());
     //System.out.println("发给群里所有在线的人"+member+":"+jsonObject.toString());
    }
   }
   break;
  case 3:
    //所有人
   for(Session s:session.getOpenSessions()){//循环发给所有在线的人
    s.getAsyncRemote().sendText(jsonObject.toString());
    //System.out.println("发给系统所有在线的人"+session.getOpenSessions()+":"+jsonObject.toString());
   }
   break;
  default:
   break;
  }
    }
    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Throwable error){
        System.out.println("llws发生错误");
        error.printStackTrace();
    }

}

猜你喜欢

转载自blog.csdn.net/qq873113580/article/details/81946367