Chinaunix首页 | 论坛 | 博客
  • 博客访问: 614282
  • 博文数量: 298
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 3077
  • 用 户 组: 普通用户
  • 注册时间: 2019-06-17 10:57
文章分类

全部博文(298)

文章存档

2022年(96)

2021年(201)

2019年(1)

我的朋友

分类: Java

2021-08-18 13:06:23

 1. 后台 启动类,执行main方法启动

点击(此处)折叠或打开

  1. package com.fh;
  2. import java.io.IOException;
  3. import java.net.InetSocketAddress;
  4. import java.net.UnknownHostException;
  5. import java.util.Date;

  6. import net.sf.json.JSONObject;

  7. import org.java_websocket.WebSocket;
  8. import org.java_websocket.WebSocketImpl;
  9. import org.java_websocket.framing.Framedata;
  10. import org.java_websocket.handshake.ClientHandshake;
  11. import org.java_websocket.server.WebSocketServer;


  12. /**
  13.  * @author FH
  14.  * from fhadmin.cn
  15.  * 2021-5-16
  16.  */
  17. public class ChatServer extends WebSocketServer{

  18.     public ChatServer(int port) throws UnknownHostException {
  19.         super(new InetSocketAddress(port));
  20.     }

  21.     public ChatServer(InetSocketAddress address) {
  22.         super(address);
  23.     }

  24.     /**
  25.      * 触发连接事件
  26.      */
  27.     @Override
  28.     public void onOpen( WebSocket conn, ClientHandshake handshake ) {
  29.         //this.sendToAll( "new connection: " + handshake.getResourceDescriptor() );
  30.         //System.out.println( conn.getRemoteSocketAddress().getAddress().getHostAddress());
  31.     }

  32.     /**
  33.      * 触发关闭事件
  34.      */
  35.     @Override
  36.     public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
  37.         userLeave(conn);
  38.     }

  39.     /**
  40.      * 客户端发送消息到服务器时触发事件
  41.      */
  42.     @Override
  43.     public void onMessage(WebSocket conn, String message){
  44.         message = message.toString();
  45.         if(null != message && message.startsWith("FHadmin313596790")){
  46.             this.userjoin(message.replaceFirst("FHadmin313596790", ""),conn);
  47.         }if(null != message && message.startsWith("LeaveFHadmin313596790")){
  48.             this.userLeave(conn);
  49.         }if(null != message && message.contains("fhadmin886")){
  50.             String toUser = message.substring(message.indexOf("fhadmin886")+10, message.indexOf("fhfhadmin888"));
  51.             message = message.substring(0, message.indexOf("fhadmin886")) +"[私信] "+ message.substring(message.indexOf("fhfhadmin888")+12, message.length());
  52.             ChatServerPool.sendMessageToUser(ChatServerPool.getWebSocketByUser(toUser),message);//向所某用户发送消息
  53.             ChatServerPool.sendMessageToUser(conn, message);//同时向本人发送消息
  54.         }else{
  55.             ChatServerPool.sendMessage(message.toString());//向所有在线用户发送消息
  56.         }
  57.     }

  58.     public void onFragment( WebSocket conn, Framedata fragment ) {
  59.     }

  60.     /**
  61.      * 触发异常事件
  62.      */
  63.     @Override
  64.     public void onError( WebSocket conn, Exception ex ) {
  65.         ex.printStackTrace();
  66.         if( conn != null ) {
  67.             //some errors like port binding failed may not be assignable to a specific websocket
  68.         }
  69.     }

  70.     
  71.     /**
  72.      * 用户加入处理
  73.      * @param user
  74.      */
  75.     public void userjoin(String user, WebSocket conn){
  76.         JSONObject result = new JSONObject();
  77.         result.element("type", "user_join");
  78.         result.element("user", "toUserMsg('"+user+"');\">"+user+"");
  79.         ChatServerPool.sendMessage(result.toString());                //把当前用户加入到所有在线用户列表中
  80.         String joinMsg = "{\"from\":\"[系统]\",\"content\":\""+user+"上线了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}";
  81.         ChatServerPool.sendMessage(joinMsg);                        //向所有在线用户推送当前用户上线的消息
  82.         result = new JSONObject();
  83.         result.element("type", "get_online_user");
  84.         ChatServerPool.addUser(user,conn);                            //向连接池添加当前的连接对象
  85.         result.element("list", ChatServerPool.getOnlineUser());
  86.         ChatServerPool.sendMessageToUser(conn, result.toString());    //向当前连接发送当前在线用户的列表
  87.     }
  88.     
  89.     /**
  90.      * 用户下线处理
  91.      * @param user
  92.      */
  93.     public void userLeave(WebSocket conn){
  94.         String user = ChatServerPool.getUserByKey(conn);
  95.         boolean b = ChatServerPool.removeUser(conn);                //在连接池中移除连接
  96.         if(b){
  97.             JSONObject result = new JSONObject();
  98.             result.element("type", "user_leave");
  99.             result.element("user", "toUserMsg('"+user+"');\">"+user+"");
  100.             ChatServerPool.sendMessage(result.toString());            //把当前用户从所有在线用户列表中删除
  101.             String joinMsg = "{\"from\":\"[系统]\",\"content\":\""+user+"下线了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}";
  102.             ChatServerPool.sendMessage(joinMsg);                    //向在线用户发送当前用户退出的消息
  103.         }
  104.     }
  105.     public static void main( String[] args ) throws InterruptedException , IOException {
  106.         WebSocketImpl.DEBUG = false;
  107.         int port = 8887; //端口
  108.         ChatServer s = new ChatServer(port);
  109.         s.start();
  110.         //System.out.println( "服务器的端口" + s.getPort() );
  111.     }

  112. }


2.ChatServerPool.java

点击(此处)折叠或打开

  1. package com.fh;

  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.Set;

  8. import org.java_websocket.WebSocket;

  9. /**
  10.  * @author FH
  11.  * from fhadmin.cn
  12.  * 2021-5-16
  13.  */
  14. public class ChatServerPool {

  15.     /*保存连接的MAP容器*/
  16.     private static final Map<WebSocket,String> userconnections = new HashMap<WebSocket,String>();
  17.     
  18.     /**
  19.      * 获取用户名
  20.      * @param session
  21.      */
  22.     public static String getUserByKey(WebSocket conn){
  23.         return userconnections.get(conn);
  24.     }
  25.     
  26.     /**
  27.      * 获取WebSocket
  28.      * @param user
  29.      */
  30.     public static WebSocket getWebSocketByUser(String user){
  31.         Set<WebSocket> keySet = userconnections.keySet();
  32.         synchronized (keySet) {
  33.             for (WebSocket conn : keySet) {
  34.                 String cuser = userconnections.get(conn);
  35.                 if(cuser.equals(user)){
  36.                     return conn;
  37.                 }
  38.             }
  39.         }
  40.         return null;
  41.     }
  42.     
  43.     /**
  44.      * 向连接池中添加连接
  45.      * @param inbound
  46.      */
  47.     public static void addUser(String user, WebSocket conn){
  48.         userconnections.put(conn,user);    //添加连接
  49.     }
  50.     
  51.     /**
  52.      * 获取所有的在线用户
  53.      * @return
  54.      */
  55.     public static Collection<String> getOnlineUser(){
  56.         List<String> setUsers = new ArrayList<String>();
  57.         Collection<String> setUser = userconnections.values();
  58.         for(String u:setUser){
  59.             setUsers.add("toUserMsg('"+u+"');\">"+u+"");
  60.         }
  61.         return setUsers;
  62.     }
  63.     
  64.     /**
  65.      * 移除连接池中的连接
  66.      * @param inbound
  67.      */
  68.     public static boolean removeUser(WebSocket conn){
  69.         if(userconnections.containsKey(conn)){
  70.             userconnections.remove(conn);    //移除连接
  71.             return true;
  72.         }else{
  73.             return false;
  74.         }
  75.     }
  76.     
  77.     /**
  78.      * 向特定的用户发送数据
  79.      * @param user
  80.      * @param message
  81.      */
  82.     public static void sendMessageToUser(WebSocket conn,String message){
  83.         if(null != conn && null != userconnections.get(conn)){
  84.             conn.send(message);
  85.         }
  86.     }
  87.     
  88.     /**
  89.      * 向所有的用户发送消息
  90.      * @param message
  91.      */
  92.     public static void sendMessage(String message){
  93.         Set<WebSocket> keySet = userconnections.keySet();
  94.         synchronized (keySet) {
  95.             for (WebSocket conn : keySet) {
  96.                 String user = userconnections.get(conn);
  97.                 if(user != null){
  98.                     conn.send(message);
  99.                 }
  100.             }
  101.         }
  102.     }
  103. }


3.前端

点击(此处)折叠或打开

  1. var websocket;
  2. var isCreatw = false;
  3. var title="";
  4. var win;
  5. var input;
  6. var isQj = true;
  7. var toUser="";
  8. function toUserMsg(toU){
  9.     if((!isQj && toUser == toU) || toU == user){
  10.         win.setTitle(title + "  (已连接) 【现在全局对话】");
  11.         isQj = true;
  12.         toUser = "";
  13.     }else{
  14.         win.setTitle(title + "  (已连接) 【现在单独与"+toU+"对话】");
  15.         isQj = false;
  16.         toUser = toU;
  17.     }
  18. }
  19.  function creatw() {
  20.              if(isCreatw){
  21.                  alert("已经启动");
  22.                  return;
  23.              }else{
  24.                  isCreatw = true;
  25.              }
  26.             //创建用户输入框
  27.             input = Ext.create('Ext.form.field.HtmlEditor', {
  28.                         region : 'south',
  29.                         height : 120,
  30.                         enableFont : false,
  31.                         enableSourceEdit : false,
  32.                         enableAlignments : false,
  33.                         listeners : {
  34.                             initialize : function() {
  35.                                 Ext.EventManager.on(me.input.getDoc(), {
  36.                                             keyup : function(e) {
  37.                                                 if (e.ctrlKey === true
  38.                                                         && e.keyCode == 13) {
  39.                                                     e.preventDefault();
  40.                                                     e.stopPropagation();
  41.                                                     send();
  42.                                                 }
  43.                                             }
  44.                                         });
  45.                             }
  46.                         }
  47.                     });
  48.             
  49.             //创建消息展示容器
  50.             var output = Ext.create('MessageContainer', {
  51.                         region : 'center'
  52.                     });

  53.             var dialog = Ext.create('Ext.panel.Panel', {
  54.                         region : 'center',
  55.                         layout : 'border',
  56.                         items : [input, output],
  57.                         buttons : [{
  58.                                     text : '发送',
  59.                                     handler : send
  60.                                 }]
  61.                     });

  62.             //初始话WebSocket
  63.             function initWebSocket() {
  64.                 if (window.WebSocket) {
  65.                     websocket = new WebSocket(encodeURI('ws://127.0.0.1:8887'));
  66.                     
  67.                     websocket.onopen = function() {
  68.                         //连接成功
  69.                         win.setTitle(title + '  (已连接) 【现在全局对话】');
  70.                         websocket.send('FHadmin313596790'+user);
  71.                     }
  72.                     websocket.onerror = function() {
  73.                         //连接失败
  74.                         win.setTitle(title + '  (连接发生错误)');
  75.                     }
  76.                     websocket.onclose = function() {
  77.                         //连接断开
  78.                         win.setTitle(title + '  (已经断开连接)');
  79.                     }
  80.                     //消息接收
  81.                     websocket.onmessage = function(message) {
  82.                         var message = JSON.parse(message.data);
  83.                         //接收用户发送的消息
  84.                         if (message.type == 'message') {
  85.                             output.receive(message);
  86.                         } else if (message.type == 'get_online_user') {
  87.                             //获取在线用户列表
  88.                             var root = onlineUser.getRootNode();
  89.                             Ext.each(message.list,function(user){
  90.                                 var node = root.createNode({
  91.                                     id : user,
  92.                                     text : user,
  93.                                     iconCls : 'user',
  94.                                     leaf : true
  95.                                 });
  96.                                 root.appendChild(node);
  97.                             });
  98.                         } else if (message.type == 'user_join') {
  99.                             //用户上线
  100.                                 var root = onlineUser.getRootNode();
  101.                                 var user = message.user;
  102.                                 var node = root.createNode({
  103.                                     id : user,
  104.                                     text : user,
  105.                                     iconCls : 'user',
  106.                                     leaf : true
  107.                                 });
  108.                                 root.appendChild(node);
  109.                         } else if (message.type == 'user_leave') {
  110.                                 //用户下线
  111.                                 var root = onlineUser.getRootNode();
  112.                                 var user = message.user;
  113.                                 var node = root.findChild('id',user);
  114.                                 root.removeChild(node);
  115.                         }
  116.                     }
  117.                 }
  118.             };

  119.             //在线用户树
  120.             var onlineUser = Ext.create('Ext.tree.Panel', {
  121.                         title : '在线用户',
  122.                         rootVisible : false,
  123.                         region : 'east',
  124.                         width : 150,
  125.                         lines : false,
  126.                         useArrows : true,
  127.                         autoScroll : true,
  128.                         split : true,
  129.                         iconCls : 'user-online',
  130.                         store : Ext.create('Ext.data.TreeStore', {
  131.                                     root : {
  132.                                         text : '在线用户',
  133.                                         expanded : true,
  134.                                         children : []
  135.                                     }
  136.                                 })
  137.                     });
  138.             
  139.             title = '欢迎您:' + user;
  140.             //展示窗口
  141.             win = Ext.create('Ext.window.Window', {
  142.                         title : title + '  (未连接)',
  143.                         layout : 'border',
  144.                         iconCls : 'user-win',
  145.                         minWidth : 650,
  146.                         minHeight : 460,
  147.                         width : 650,
  148.                         animateTarget : 'websocket_button',
  149.                         height : 460,
  150.                         items : [dialog,onlineUser],
  151.                         border : false,
  152.                         listeners : {
  153.                             render : function() {
  154.                                 initWebSocket();
  155.                             }
  156.                         }
  157.                     });

  158.             win.show();
  159.             
  160.             win.on("close",function(){
  161.                 websocket.send('LeaveFHadmin313596790');
  162.                 isCreatw = false;
  163.              });

  164.             //发送消息
  165.             function send() {
  166.                 var content = input.getValue();
  167.                 if(toUser != ""){content = "fhadmin886"+toUser+"fhfhadmin888" + content;}
  168.                 var message = {};
  169.                 if (websocket != null) {
  170.                     if (input.getValue()) {
  171.                         Ext.apply(message, {
  172.                                     from : user,
  173.                                     content : content,
  174.                                     timestamp : new Date().getTime(),
  175.                                     type : 'message'
  176.                                 });
  177.                         websocket.send(JSON.stringify(message));
  178.                         //output.receive(message);
  179.                         input.setValue('');
  180.                     }
  181.                 } else {
  182.                     Ext.Msg.alert('提示', '您已经掉线,无法发送消息!');
  183.                 }
  184.             }
  185. };

  186. //用于展示用户的聊天信息
  187. Ext.define('MessageContainer', {

  188.     extend : 'Ext.view.View',

  189.     trackOver : true,

  190.     multiSelect : false,

  191.     itemCls : 'l-im-message',

  192.     itemSelector : 'div.l-im-message',

  193.     overItemCls : 'l-im-message-over',

  194.     selectedItemCls : 'l-im-message-selected',

  195.     style : {
  196.         overflow : 'auto',
  197.         backgroundColor : '#fff'
  198.     },

  199.     tpl : [
  200.             '
    欢迎使用FH Admin 即时通讯系统。
    '
    ,
  201.             '',
  202.             '
    ',
  203.             '
    {from} {timestamp}
    '
    ,
  204.             '
    {content}
    '
    , '
',
  •             ''],

  •     messages : [],

  •     initComponent : function() {
  •         var me = this;
  •         me.messageModel = Ext.define('Leetop.im.MessageModel', {
  •                     extend : 'Ext.data.Model',
  •                     fields : ['from', 'timestamp', 'content', 'source']
  •                 });
  •         me.store = Ext.create('Ext.data.Store', {
  •                     model : 'Leetop.im.MessageModel',
  •                     data : me.messages
  •                 });
  •         me.callParent();
  •     },

  •     //将服务器推送的信息展示到页面中
  •     receive : function(message) {
  •         var me = this;
  •         message['timestamp'] = Ext.Date.format(new Date(message['timestamp']),
  •                 'H:i:s');
  •         if(message.from == user){
  •             message.source = 'self';
  •         }else{
  •             message.source = 'remote';
  •         }
  •         me.store.add(message);
  •         if (me.el.dom) {
  •             me.el.dom.scrollTop = me.el.dom.scrollHeight;
  •         }
  •     }
  • })

  • 阅读(911) | 评论(0) | 转发(0) |
    给主人留下些什么吧!~~