var wsUri = "ws://localhost/Websocket/IMSer...">
赞
踩
目录
前台页面代码
-
- <script type="text/javascript">
-
- var wsUri = "ws://localhost/Websocket/IMServer?userid=rz_${rybh}&username=${XM}";
- var socket = new WebSocket(wsUri);
- //发送消息
- socket.send(message);
- //websocket建立连接
- socket.onopen = function(evt) {
-
- };
- //websocket监听接收消息
- socket.onmessage = function(evt) {
-
- }
-
- </script>
IMserver.java
- package com.test;
-
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.net.URLDecoder;
- import java.util.HashMap;
- import java.util.Map;
-
- import javax.websocket.OnClose;
- import javax.websocket.OnMessage;
- import javax.websocket.OnOpen;
- import javax.websocket.Session;
- import javax.websocket.server.ServerEndpoint;
-
- import com.google.gson.Gson;
-
- /**
- * 桌面窗口对话服务端
- * 标识 userid+DESKSERVER
- *
- */
- @ServerEndpoint("/IMServer")
- public class EchoServer {
- String fgf="###"; //分隔符
- private String toUser;
-
- private String userid;//消息发送人id
- private String username;//消息发送人姓名
- private String fromUser;
- private String hyid;//会话id
-
- public String getHyid() {
- return hyid;
- }
-
- public void setHyid(String hyid) {
- this.hyid = hyid;
- }
-
- public String getUserid() {
- return userid;
- }
-
- public void setUserid(String userid) {
- this.userid = userid;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getFromUser() {
- return fromUser;
- }
-
- public void setFromUser(String fromUser) {
- this.fromUser = fromUser;
- }
-
- public String getToUser() {
- return toUser;
- }
-
- public void setToUser(String toUser) {
- this.toUser = toUser;
- }
-
- @OnOpen
- public void initSession(Session session) throws UnsupportedEncodingException {
- this.setToUser(session.getRequestParameterMap().get("toUser").get(0));
- this.setUserid(session.getRequestParameterMap().get("userid").get(0));
- this.setUsername(URLDecoder.decode(session.getRequestParameterMap().get("username").get(0)+"","UTF-8"));
- this.setHyid(session.getRequestParameterMap().get("hyid").get(0));
-
- SessionMap.sessions.put(this.getUserid()+"DESKSERVER", session);//DESKSERVER桌面聊天设置
- //SessionUtil.sessions.add(session);
- }
-
- @OnMessage
- public void echo(String incomingMessage){
- // System.err.println("发送消息内容:"+incomingMessage);
- String hyids=this.getToUser();
- if(null!=hyids&&!"".equals(hyids)){
-
- String[] ryids = hyids.split(",");
- for(int i=0;i<ryids.length;i++){
- // System.err.println("发送消息给::"+ryids[i]);
- Session session=SessionMap.sessions.get(ryids[i]);
- String[] incomingMessages=incomingMessage.split(fgf);
- if(session!=null){
- Map<String, Object> map=new HashMap<String, Object>();
- map.put("Msgsdate",incomingMessages[1]);//消息发送时间
- map.put("Msgsreturnid",incomingMessages[2]);//消息id
- map.put("Msgs",incomingMessages[0]);//消息
- map.put("SenderId", this.getUserid());//发送人id
- map.put("SenderName", this.getUsername());//发送人姓名
- map.put("hyid", this.getHyid());//发送人姓名
- String json=new Gson().toJson(map);
- sendMessage(session, json);
- }
- }
- }
- }
-
-
- private void sendMessage(Session session, String msg) {
- try {
- session.getBasicRemote().sendText(msg);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- // @OnError
- // public void processError(Session session){
- // SessionUtil.sessions.remove(session);
- // }
-
- @OnClose
- public void processClose(Session session){
- SessionMap.sessions.remove(this.getUserid()+"DESKSERVER");
- }
-
- }
结合 layim
- layui.use('layim',function(layim) {
-
- //基础配置
- layim.config({
-
- //或采用以下方式初始化接口
- //或采用以下方式初始化接口
- init : {
- url : '${ctx}/api/layui/lxrlist',
- data : {}
- }
- //查看群员接口
- ,members : {
- url : '${ctx}/api/layui/qzrylist',
- data : {}
- }
- //上传图片接口
- ,
- uploadImage : {
- url : '${ctx}/api/layui/fileUpload' //(返回的数据格式见下文)
- ,
- type : '' //默认post
- }
- //上传文件接口
- ,
- uploadFile : {
- url : '${ctx}/api/layui/fileUploadfile' //(返回的数据格式见下文)
- ,
- type : '' //默认post
- }
- //扩展工具栏
- // ,tool: [{
- // alias: 'code'
- // ,title: '代码'
- // ,icon: ''
- // }]
- //,brief: true //是否简约模式(若开启则不显示主面板)
- ,
- title : '即时通讯' //自定义主面板最小化时的标题
- //,right: '100px' //主面板相对浏览器右侧距离
- //,minRight: '90px' //聊天面板最小化时相对浏览器右侧距离
- ,
- //right: '15%', //主面板相对浏览器右侧距离
- //minRight: '200px',//用户控制聊天面板最小化时、及新消息提示层的相对right的px坐标。
- initSkin : '3.jpg' //1-5 设置初始背景
- //,skin: ['aaa.jpg'] //新增皮肤
- //,isfriend: false //是否开启好友
- ,
- isgroup : true //是否开启群组
- ,
- min : true //是否始终最小化主面板,默认false
- ,
- notice : true //是否开启桌面消息提醒,默认false
- ,
- voice : false //声音提醒,默认开启,声音文件为:default.wav
- ,
- copyright : true
- // ,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/chat.jsp' //聊天记录页面地址,若不开启,剔除该项即可
-
- });
-
- /* var cache = layui.layim.cache();
- var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据
-
- //这里以删除本地聊天记录为例
- delete local.chatlog;
-
- //向localStorage同步数据
- layui.data('layim', {
- key: cache.mine.id
- ,value: local
- }); */
-
-
- //监听在线状态的切换事件
- layim.on('online', function(data) {
- //console.log(data);
- });
-
- //监听签名修改
- layim.on('sign', function(value) {
- //console.log(value);
- });
-
- //监听自定义工具栏点击,以添加代码为例
- // 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建立就绪
- layim.on('ready', function(res) {
- //console.log(res.mine);
- //layim.msgbox(5); //模拟消息盒子有新消息,实际使用时,一般是动态获得
- setTimeout(function() {
- var obj = {};
- //接受消息(如果检测到该socket)
- }, 3000);
- });
- // 打开layim时建立websocket服务端连接
- var wsUri = "ws://localhost/Websocket/IMServer?userid=rz_${rybh}&username=${XM}";
- var socket = new WebSocket(wsUri);
- //监听发送消息
- layim.on('sendMessage', function(data) {
- var To = data.to;
- if (To.type === 'friend') {
- socket.send(data.to.id + "#@@#" + JSON.stringify(data)); //websocket 发送消息
- }
- //发送消息内容持久化
- $.ajax({
- type : 'post',
- data : {
- key : JSON.stringify(data)
- },
- url : '${ctx}/api/layui/sendmessage',
- success : function(val) {
- }
- });
-
- });
- //websocket建立连接
- socket.onopen = function(evt) {
- };
- //websocket监听接收消息
- socket.onmessage = function(evt) {
- evt = JSON.parse(evt.data);
- layim.getMessage({
- username : evt.mine.username, //消息来源用户名
- avatar : evt.mine.avatar, //消息来源用户头像
- id : evt.mine.id, //消息的来源ID(如果是私聊,则是用户id,如果是群聊,则是群组id)
- type : evt.to.type, //聊天窗口来源类型,从发送消息传递的to里面获取
- content : evt.mine.content, //消息内容
- cid : 0, //消息id,可不传。除非你要对消息进行一些操作(如撤回)
- mine : false, //是否我发送的消息,如果为true,则会显示在右方
- fromid : evt.mine.id //消息的发送者id(比如群组中的某个消息发送者),可用于自动解决浏览器多窗口时的一些问题
- timestamp : new Date().getTime()//服务端动态时间戳
- });
- };
- socket.onerror = function(evt) {
- // console.log("ERROR!!!!");
- //writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
- //socket.close();
- };
-
- //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
- window.onbeforeunload = function () {
- socket.close();
- };
- //监听查看群员
- layim.on('members', function(data) {
- //console.log(data);
- });
- //监听聊天窗口的切换
- layim.on('chatChange', function(res) {
- var type = res.data.type;
- });
-
- });
MyClient.java websocket客户端
- package com.utils.websocket;
-
- import javax.websocket.ClientEndpoint;
- import javax.websocket.OnClose;
- import javax.websocket.OnError;
- import javax.websocket.OnMessage;
- import javax.websocket.OnOpen;
- import javax.websocket.Session;
-
- @ClientEndpoint
- public class MyClient {
- @OnOpen
- public void onOpen(Session session) {
- }
- @OnMessage
- public void onMessage(String message) {
- }
- @OnClose
- public void processClose(Session session){
-
- }
- @OnError
- public void onError(Throwable t) {
- t.printStackTrace();
- }
- }
ConnToServer.java 连接websocket服务端
- package com.utils.websocket;
-
- import java.io.IOException;
- import java.net.URI;
- import java.net.URISyntaxException;
-
- import javax.websocket.ContainerProvider;
- import javax.websocket.DeploymentException;
- import javax.websocket.Session;
- import javax.websocket.WebSocketContainer;
-
- public class ConnToServer {
-
- public Session session;
-
- /**
- * 连接websocket server
- * @param uri
- */
- public void start(String uri) {
- WebSocketContainer container = ContainerProvider.getWebSocketContainer();
-
- try {
- session = container.connectToServer(MyClient.class, new URI(uri));
- } catch (DeploymentException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (URISyntaxException e) {
- e.printStackTrace();
- }
- }
- }
PushMsg.java 消息发送工具类
- package com.test.push;
-
- import java.net.URI;
- import java.net.URLEncoder;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
-
- import org.apache.log4j.Logger;
-
- import com.fasterxml.jackson.dataformat.yaml.snakeyaml.util.UriEncoder;
- import com.utils.websocket.ConnToServer;
-
- /**
- * 消息发送工具类
- *
- * @author Administrator
- *
- */
- public final class PushMsg {
-
- private PushMsg(){};
-
- private static Logger logger = Logger.getLogger(PushMsg.class);
-
- /**给指定的人发送消息提醒
- *
- * @param message (消息内容)
- * @param userId (发送对象)
- */
- public static void sendMessage(Message message) {
- try {
- // 推送消息
- List<Map<String, Object>> list=message.getMsgDatas();
- if(!list.isEmpty()&&list.size()>0){
- Map<String, Object> map=list.get(0);
- String username=map.get("xm")+"";
- String sender=map.get("sender")+"";
- String reciver=map.get("reciver")+"";
- String content=map.get("content")+"";
- username=URLEncoder.encode(username,"UTF-8");
- //建立连接,发送消息
- String uri = "ws://localhost:1234/websocket/echo?sender="+sender+"&username="+username+"&reciver="+reciver;
- ConnToServer cts=new ConnToServer();
- cts.start(uri);//
- cts.session.getBasicRemote().sendText(content);
- cts.session.close();
- }
-
- } catch (Exception e) {
- logger.error(e.getCause());
- }
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。