java WebSocket 即時通訊配置使用說明

FH-Admin發表於2021-08-18

1. 後臺 啟動類,執行main方法啟動

package com.fh;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Date;

import net.sf.json.JSONObject;

import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

/**
 * @author FH
 * from fhadmin.cn
 * 2021-5-16
 */
public class ChatServer extends WebSocketServer{

    public ChatServer(int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
    }

    public ChatServer(InetSocketAddress address) {
        super(address);
    }

    /**
     * 觸發連線事件
     */
    @Override
    public void onOpen( WebSocket conn, ClientHandshake handshake ) {
        //this.sendToAll( "new connection: " + handshake.getResourceDescriptor() );
        //System.out.println( conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    /**
     * 觸發關閉事件
     */
    @Override
    public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
        userLeave(conn);
    }

    /**
     * 客戶端傳送訊息到伺服器時觸發事件
     */
    @Override
    public void onMessage(WebSocket conn, String message){
        message = message.toString();
        if(null != message && message.startsWith("FHadmin313596790")){
            this.userjoin(message.replaceFirst("FHadmin313596790", ""),conn);
        }if(null != message && message.startsWith("LeaveFHadmin313596790")){
            this.userLeave(conn);
        }if(null != message && message.contains("fhadmin886")){
            String toUser = message.substring(message.indexOf("fhadmin886")+10, message.indexOf("fhfhadmin888"));
            message = message.substring(0, message.indexOf("fhadmin886")) +"[私信]  "+ message.substring(message.indexOf("fhfhadmin888")+12, message.length());
            ChatServerPool.sendMessageToUser(ChatServerPool.getWebSocketByUser(toUser),message);//向所某使用者傳送訊息
            ChatServerPool.sendMessageToUser(conn, message);//同時向本人傳送訊息
        }else{
            ChatServerPool.sendMessage(message.toString());//向所有線上使用者傳送訊息
        }
    }

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

    /**
     * 觸發異常事件
     */
    @Override
    public void onError( WebSocket conn, Exception ex ) {
        ex.printStackTrace();
        if( conn != null ) {
            //some errors like port binding failed may not be assignable to a specific websocket
        }
    }

    /**
     * 使用者加入處理
     * @param user
     */
    public void userjoin(String user, WebSocket conn){
        JSONObject result = new JSONObject();
        result.element("type", "user_join");
        result.element("user", "<a onclick=\"toUserMsg('"+user+"');\">"+user+"</a>");
        ChatServerPool.sendMessage(result.toString());                //把當前使用者加入到所有線上使用者列表中
        String joinMsg = "{\"from\":\"[系統]\",\"content\":\""+user+"上線了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}";
        ChatServerPool.sendMessage(joinMsg);                        //向所有線上使用者推送當前使用者上線的訊息
        result = new JSONObject();
        result.element("type", "get_online_user");
        ChatServerPool.addUser(user,conn);                            //向連線池新增當前的連線物件
        result.element("list", ChatServerPool.getOnlineUser());
        ChatServerPool.sendMessageToUser(conn, result.toString());    //向當前連線傳送當前線上使用者的列表
    }

    /**
     * 使用者下線處理
     * @param user
     */
    public void userLeave(WebSocket conn){
        String user = ChatServerPool.getUserByKey(conn);
        boolean b = ChatServerPool.removeUser(conn);                //在連線池中移除連線
        if(b){
            JSONObject result = new JSONObject();
            result.element("type", "user_leave");
            result.element("user", "<a onclick=\"toUserMsg('"+user+"');\">"+user+"</a>");
            ChatServerPool.sendMessage(result.toString());            //把當前使用者從所有線上使用者列表中刪除
            String joinMsg = "{\"from\":\"[系統]\",\"content\":\""+user+"下線了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}";
            ChatServerPool.sendMessage(joinMsg);                    //向線上使用者傳送當前使用者退出的訊息
        }
    }
    public static void main( String[] args ) throws InterruptedException , IOException {
        WebSocketImpl.DEBUG = false;
        int port = 8887; //埠
        ChatServer s = new ChatServer(port);
        s.start();
        //System.out.println( "伺服器的埠" + s.getPort() );
    }

}

2.ChatServerPool.java

package com.fh;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.java_websocket.WebSocket;

/**
 * @author FH
 * from fhadmin.cn
 * 2021-5-16
 */
public class ChatServerPool {

    /*儲存連線的MAP容器*/
    private static final Map<WebSocket,String> userconnections = new HashMap<WebSocket,String>();

    /**
     * 獲取使用者名稱
     * @param session
     */
    public static String getUserByKey(WebSocket conn){
        return userconnections.get(conn);
    }

    /**
     * 獲取WebSocket
     * @param user
     */
    public static WebSocket getWebSocketByUser(String user){
        Set<WebSocket> keySet = userconnections.keySet();
        synchronized (keySet) {
            for (WebSocket conn : keySet) {
                String cuser = userconnections.get(conn);
                if(cuser.equals(user)){
                    return conn;
                }
            }
        }
        return null;
    }

    /**
     * 向連線池中新增連線
     * @param inbound
     */
    public static void addUser(String user, WebSocket conn){
        userconnections.put(conn,user);    //新增連線
    }

    /**
     * 獲取所有的線上使用者
     * @return
     */
    public static Collection<String> getOnlineUser(){
        List<String> setUsers = new ArrayList<String>();
        Collection<String> setUser = userconnections.values();
        for(String u:setUser){
            setUsers.add("<a onclick=\"toUserMsg('"+u+"');\">"+u+"</a>");
        }
        return setUsers;
    }

    /**
     * 移除連線池中的連線
     * @param inbound
     */
    public static boolean removeUser(WebSocket conn){
        if(userconnections.containsKey(conn)){
            userconnections.remove(conn);    //移除連線
            return true;
        }else{
            return false;
        }
    }

    /**
     * 向特定的使用者傳送資料
     * @param user
     * @param message
     */
    public static void sendMessageToUser(WebSocket conn,String message){
        if(null != conn && null != userconnections.get(conn)){
            conn.send(message);
        }
    }

    /**
     * 向所有的使用者傳送訊息
     * @param message
     */
    public static void sendMessage(String message){
        Set<WebSocket> keySet = userconnections.keySet();
        synchronized (keySet) {
            for (WebSocket conn : keySet) {
                String user = userconnections.get(conn);
                if(user != null){
                    conn.send(message);
                }
            }
        }
    }
}

3.前端


var websocket;
var isCreatw = false;
var title="";
var win;
var input;
var isQj = true;
var toUser="";
function toUserMsg(toU){
    if((!isQj && toUser == toU) || toU == user){
        win.setTitle(title + "&nbsp;&nbsp;(已連線)   【現在全域性對話】");
        isQj = true;
        toUser = "";
    }else{
        win.setTitle(title + "&nbsp;&nbsp;(已連線)   【現在單獨與"+toU+"對話】");
        isQj = false;
        toUser = toU;
    }
}
 function creatw() {
             if(isCreatw){
                 alert("已經啟動");
                 return;
             }else{
                 isCreatw = true;
             }
            //建立使用者輸入框
            input = Ext.create('Ext.form.field.HtmlEditor', {
                        region : 'south',
                        height : 120,
                        enableFont : false,
                        enableSourceEdit : false,
                        enableAlignments : false,
                        listeners : {
                            initialize : function() {
                                Ext.EventManager.on(me.input.getDoc(), {
                                            keyup : function(e) {
                                                if (e.ctrlKey === true
                                                        && e.keyCode == 13) {
                                                    e.preventDefault();
                                                    e.stopPropagation();
                                                    send();
                                                }
                                            }
                                        });
                            }
                        }
                    });

            //建立訊息展示容器
            var output = Ext.create('MessageContainer', {
                        region : 'center'
                    });

            var dialog = Ext.create('Ext.panel.Panel', {
                        region : 'center',
                        layout : 'border',
                        items : [input, output],
                        buttons : [{
                                    text : '傳送',
                                    handler : send
                                }]
                    });

            //初始話WebSocket
            function initWebSocket() {
                if (window.WebSocket) {
                    websocket = new WebSocket(encodeURI('ws://127.0.0.1:8887'));

                    websocket.onopen = function() {
                        //連線成功
                        win.setTitle(title + '&nbsp;&nbsp;(已連線)   【現在全域性對話】');
                        websocket.send('FHadmin313596790'+user);
                    }
                    websocket.onerror = function() {
                        //連線失敗
                        win.setTitle(title + '&nbsp;&nbsp;(連線發生錯誤)');
                    }
                    websocket.onclose = function() {
                        //連線斷開
                        win.setTitle(title + '&nbsp;&nbsp;(已經斷開連線)');
                    }
                    //訊息接收
                    websocket.onmessage = function(message) {
                        var message = JSON.parse(message.data);
                        //接收使用者傳送的訊息
                        if (message.type == 'message') {
                            output.receive(message);
                        } else if (message.type == 'get_online_user') {
                            //獲取線上使用者列表
                            var root = onlineUser.getRootNode();
                            Ext.each(message.list,function(user){
                                var node = root.createNode({
                                    id : user,
                                    text : user,
                                    iconCls : 'user',
                                    leaf : true
                                });
                                root.appendChild(node);
                            });
                        } else if (message.type == 'user_join') {
                            //使用者上線
                                var root = onlineUser.getRootNode();
                                var user = message.user;
                                var node = root.createNode({
                                    id : user,
                                    text : user,
                                    iconCls : 'user',
                                    leaf : true
                                });
                                root.appendChild(node);
                        } else if (message.type == 'user_leave') {
                                //使用者下線
                                var root = onlineUser.getRootNode();
                                var user = message.user;
                                var node = root.findChild('id',user);
                                root.removeChild(node);
                        }
                    }
                }
            };

            //線上使用者樹
            var onlineUser = Ext.create('Ext.tree.Panel', {
                        title : '線上使用者',
                        rootVisible : false,
                        region : 'east',
                        width : 150,
                        lines : false,
                        useArrows : true,
                        autoScroll : true,
                        split : true,
                        iconCls : 'user-online',
                        store : Ext.create('Ext.data.TreeStore', {
                                    root : {
                                        text : '線上使用者',
                                        expanded : true,
                                        children : []
                                    }
                                })
                    });

            title = '歡迎您:' + user;
            //展示視窗
            win = Ext.create('Ext.window.Window', {
                        title : title + '&nbsp;&nbsp;(未連線)',
                        layout : 'border',
                        iconCls : 'user-win',
                        minWidth : 650,
                        minHeight : 460,
                        width : 650,
                        animateTarget : 'websocket_button',
                        height : 460,
                        items : [dialog,onlineUser],
                        border : false,
                        listeners : {
                            render : function() {
                                initWebSocket();
                            }
                        }
                    });

            win.show();

            win.on("close",function(){
                websocket.send('LeaveFHadmin313596790');
                isCreatw = false;
             });

            //傳送訊息
            function send() {
                var content = input.getValue();
                if(toUser != ""){content = "fhadmin886"+toUser+"fhfhadmin888" + content;}
                var message = {};
                if (websocket != null) {
                    if (input.getValue()) {
                        Ext.apply(message, {
                                    from : user,
                                    content : content,
                                    timestamp : new Date().getTime(),
                                    type : 'message'
                                });
                        websocket.send(JSON.stringify(message));
                        //output.receive(message);
                        input.setValue('');
                    }
                } else {
                    Ext.Msg.alert('提示', '您已經掉線,無法傳送訊息!');
                }
            }
};

//用於展示使用者的聊天資訊
Ext.define('MessageContainer', {

    extend : 'Ext.view.View',

    trackOver : true,

    multiSelect : false,

    itemCls : 'l-im-message',

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

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

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

    style : {
        overflow : 'auto',
        backgroundColor : '#fff'
    },

    tpl : [
            '<div class="l-im-message-warn">​歡迎使用FH Admin 即時通訊系統。</div>',
            '<tpl for=".">',
            '<div class="l-im-message">',
            '<div class="l-im-message-header l-im-message-header-{source}">{from}  {timestamp}</div>',
            '<div class="l-im-message-body">{content}</div>', '</div>',
            '</tpl>'],

    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;
        }
    }
});
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章