1. 程式人生 > >webSocket 實現 客服聊天邏輯

webSocket 實現 客服聊天邏輯

文章目錄

寫在前面

	程式碼基本都是網上百度的,自己根據業務需要,進行了一些修改。
	前端頁面不擅長除錯,基本邏輯完成了,可以用 tab 選項卡來展示不同的聊天人員
	給有需要的人。大神輕噴。

程式碼

前端

客服端

<!DOCTYPE html>
<html>
<
head
>
<title>Java後端WebSocket的Tomcat實現</title>       <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport' />       <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <h1
>
客服介面</h1> 內容:<input id="text" type="text"/> 使用者:<input id="user" type="text"/> <button onclick="send()">傳送訊息</button> <hr/> <button onclick="closeWebSocket()">關閉WebSocket連線</button> <hr/> <div id="message"></div> </
body
>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> var websocket = null; //判斷當前瀏覽器是否支援WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:8887"); } else { alert('當前瀏覽器 Not support websocket') } //連線發生錯誤的回撥方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket連線發生錯誤"); }; //連線成功建立的回撥方法 websocket.onopen = function () { // 連線成功,註冊自己 websocket.send("register|admin"); } //接收到訊息的回撥方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //連線關閉的回撥方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket連線關閉"); } //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,server端會拋異常。 window.onbeforeunload = function () { closeWebSocket(); } //將訊息顯示在網頁上 function setMessageInnerHTML(innerHTML) { var contents = innerHTML.split("|"); if($("#"+contents[1]).length > 0){ $("#"+contents[1]).append("<font color=red>"+contents[1]+":"+contents[2]+"<br/></font>") }else{ document.getElementById('message').innerHTML += '<div id='+contents[1]+' style="display:inline-block;border:1px solid red;width:200px;height:200px" >'+"<font color=red>"+ contents[1]+":"+contents[2] + '<br/></font>'+'</div> '; } } //關閉WebSocket連線 function closeWebSocket() { websocket.close(); } //傳送訊息 function send() { var message = document.getElementById('text').value; var user = document.getElementById('user').value; $("#"+user).append("<font color=green>"+"我:"+message+"<br/></font>") websocket.send("chat|"+user+"|"+message); } </script> </html>

使用者端

<!DOCTYPE html>
<html>
<head>
    <title>Java後端WebSocket的Tomcat實現</title>
      <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport' />
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
    <h1>使用者介面</h1>
    內容:<input id="text" type="text"/>
    <button onclick="send()">傳送訊息</button>
    <hr/>
    <button onclick="closeWebSocket()">關閉WebSocket連線</button>
    <hr/>
    <div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;
    //判斷當前瀏覽器是否支援WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8887");
    }
    else {
        alert('當前瀏覽器 Not support websocket')
    }

    //連線發生錯誤的回撥方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket連線發生錯誤");
    };

    //連線成功建立的回撥方法
    websocket.onopen = function () {
        // 連線成功,註冊自己
        websocket.send("register|"+new Date().getTime());
    }

    //接收到訊息的回撥方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //連線關閉的回撥方法
    websocket.onclose = function () {
        setMessageInnerHTML("WebSocket連線關閉");
    }

    //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket連線,防止連線還沒斷開就關閉視窗,server端會拋異常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //將訊息顯示在網頁上
    function setMessageInnerHTML(innerHTML) {
        var contents = innerHTML.split("|");
        document.getElementById('message').innerHTML +="<font color=red>"+ "客服:"+ contents[2] + '<br/></font>';
    }

    //關閉WebSocket連線
    function closeWebSocket() {
        websocket.close();
    }

    //傳送訊息
    function send() {
        var message = document.getElementById('text').value;
        document.getElementById('message').innerHTML +="<font color=green>"+ "我:" + message + '<br/></font>';
        websocket.send("chat|admin|"+message);
    }
</script>
</html>

後端

各事件處理類

package WebSocket;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * @author kangxuan
 * @date 2018/3/13 18:32
 * @description
 */
public class WebSocketEntity extends WebSocketServer {

    public WebSocketEntity(int port) {
        super(new InetSocketAddress(port));
    }

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


    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        System.out.println();
        System.out.println("==============================開啟連線===============================");
    }



    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        System.out.println();
        System.out.println("================================關閉連線==============================");
    }

    @Override
    public void onMessage(WebSocket webSocket, String s) {
        System.out.println();
        System.out.println("==============================接收訊息================================");
        System.out.println("接受到的訊息:"+s);

        InetSocketAddress remoteSocketAddress = webSocket.getRemoteSocketAddress();
        int port = remoteSocketAddress.getPort();
        String[] split = s.split("\\|");
        if (s.startsWith("register")){ // 註冊

            WebSocketPool.addConn(split[1],webSocket);
        }else if (s.startsWith("chat")){// 聊天
            WebSocket conn = WebSocketPool.getConn(split[1]);
            // 根據連接獲取使用者

            conn.send("response|"+WebSocketPool.getUserBySocket(webSocket)+"|"+split[2]);
        }

        if ("@heart".equals(s)){
            System.out.println("-------------接受到心跳包"
            );
        }
    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {
        System.out.println();
        System.out.println("==============================錯誤==================================");
    }
}

socket連線管理類

package WebSocket;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

import org.java_websocket.WebSocket;

/**
 * @author kangxuan
 * @date 2018/3/13 18:27
 * @description
 */
public class WebSocketPool {
    private static Map<String, WebSocket> map = new HashMap<>();
    private static Map<String,String> webSocketUserMap = new HashMap<>();

    /**
     * 存入socket連線
     */
    public static void addConn(String name, WebSocket conn) {
        map.put(name,conn);
        webSocketUserMap.put(getKey(conn),name);
    }

    /**
     * 獲取 socket連線對應的使用者
     */
    public static String getUserBySocket(WebSocket webSocket){
        return webSocketUserMap.get(getKey(webSocket));
    }

    /**
     * 獲取 webSocket唯一連線
     * @param webSocket
     * @return
     */
    private static String getKey(WebSocket webSocket){
        InetSocketAddress remoteSocketAddress = webSocket.getRemoteSocketAddress();
        return remoteSocketAddress.getAddress().getHostAddress()+":"+remoteSocketAddress.getPort();
    };

    /**
     * 取出socket連線
     */
    public static WebSocket getConn(String name) {
        WebSocket webSocket = map.get(name);
        return webSocket;
    }

    /**
     * 給所有使用者發信息
     */
    public static void sendToAll(WebSocket webSocket,String msg){
        for (Map.Entry<String, WebSocket> stringWebSocketEntry : map.entrySet()) {
            String key = stringWebSocketEntry.getKey();
            WebSocket value = stringWebSocketEntry.getValue();
            int port = webSocket.getRemoteSocketAddress().getPort();
            if (!String.valueOf(port).equals(key)){
                value.send(port+":"+msg);
            }

        }
    }
}

測試類

package WebSocket;

import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;

import java.util.Scanner;

/**
 * @author kangxuan
 * @date 2018/3/13 18:26
 * @description
 */
public class WebSocketTest {
    public static void main(String[] args) {
        WebSocketImpl.DEBUG = false;
        int port = 8887; // 埠
        WebSocketEntity s = new WebSocketEntity(port);
        s.start();
    }
}

效果圖

在這裡插入圖片描述