webSocket 实现 客服聊天逻辑

文章目录

  • 写在前面
  • 代码
    • 前端
      • 客服端
      • 用户端
    • 后端
      • 各事件处理类
      • socket连接管理类
      • 测试类
  • 效果图
  • 源码

写在前面

	代码基本都是网上百度的,自己根据业务需要,进行了一些修改。
	前端页面不擅长调试,基本逻辑完成了,可以用 tab 选项卡来展示不同的聊天人员
	给有需要的人。大神轻喷。

代码

前端

客服端


<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(""+contents[1]+":"+contents[2]+"
"
) }else{ document.getElementById('message').innerHTML += '
'+""+ contents[1]+":"+contents[2] + '
'+'
'
; } } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } //发送消息 function send() { var message = document.getElementById('text').value; var user = document.getElementById('user').value; $("#"+user).append(""+"我:"+message+"
"
) websocket.send("chat|"+user+"|"+message); }
script> 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 +=""+ "客服:"+ contents[2] + '
'
; } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } //发送消息 function send() { var message = document.getElementById('text').value; document.getElementById('message').innerHTML +=""+ "我:" + message + '
'
; 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();
    }
}

效果图

webSocket 实现 客服聊天逻辑_第1张图片

源码

其实我粘贴出来的基本就是源码了,只差了一个websocket的jar包,我把源码放到百度盘了,有需要的下载吧!
链接:https://pan.baidu.com/s/11SajF8hlNIfo3KPA_-xZIA
提取码:iyld
复制这段内容后打开百度网盘手机App,操作更方便哦

你可能感兴趣的:(java)