Java WebSocket 基于spring + stomp + SimpMessagingTemplate支持IE9

简述:支持发送公告、发送指定用户及异地登录。

spring mvc需要的jar包:


image.png

使用spring boot 可以集成websocket库,如果少了其他库,可以在启动spring boot项目看控制台报什么错,再添加相对应的库即可。

需要的JavaScript库:
sockjs.js
stomp.js

定义收发消息实体类:

package com.test.springWebsocket;

public class WebMessage {

    /**
     * 用户id
     */
    private Long userId;

    /**
     * 用户名
     */
    private String username;

    /**
     * 客户端标记
     */
    private String clientMark;

    /**
     * 内容
     */
    private String contents;

    /**
     * 消息类型,1.公告,2.点对点发消息,3.检查异地登录
     */
    private String type;

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getClientMark() {
        return clientMark;
    }

    public void setClientMark(String clientMark) {
        this.clientMark = clientMark;
    }

    public String getContents() {
        return contents;
    }

    public void setContents(String contents) {
        this.contents = contents;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

定义WebSocket配置:

package com.test.springWebsocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        //客户端与服务器端建立连接的点,允许使用sockJs方式访问,允许跨域
        stompEndpointRegistry.addEndpoint("/any-socket").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
        //订阅Broker名称
        messageBrokerRegistry.enableSimpleBroker("/topic", "/user");
        //全局使用的订阅前缀(客户端订阅路径上会体现出来)
        messageBrokerRegistry.setApplicationDestinationPrefixes("/app");
        //点对点使用的订阅前缀(客户端订阅路径上会体现出来),不设置的话,默认也是/user/
        //注意:enableSimpleBroker方法里的某个参数路径必须和该方法的路径要一样,不然指定用户发送消息将会失败
        messageBrokerRegistry.setUserDestinationPrefix("/user/");
    }
}

定义WebSocketController:

package com.test.springWebsocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate template;

    /**
     * 发送公告
     *
     * @param msg WebMessage
     */
    @MessageMapping("/to-all")
    public void toAll(WebMessage msg) {
        template.convertAndSend("/topic/to-all", msg);
    }

    /**
     * 发送指定用户
     *
     * @param msg WebMessage
     */
    @MessageMapping("/to-one")
    public void toOne(WebMessage msg) {
        Long userId = msg.getUserId();
        if (userId != null) {
            template.convertAndSendToUser(userId.toString(), "/to-one", msg);
        }
    }
}

定义jsp页面RequestMapping:

   /**
     * spring WebSocket 页面
     *
     * @param request HttpServletRequest
     * @return String
     */
    @RequestMapping("/spring-websocket.xhtm")
    public String springWebsocket(HttpServletRequest request) {
        String clientMark = (String) request.getSession().getAttribute("clientMark");
        if (clientMark == null) {
            clientMark = GenerateUtil.getUUID();
            request.getSession().setAttribute("clientMark", clientMark);
        }
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        request.setAttribute("userId", admin.getId());
        request.setAttribute("username", admin.getAdmin());
        request.setAttribute("clientMark", clientMark);
        return "springWebsocket/springWebsocket";
    }

定义jsp页面:

<!DOCTYPE html>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%
    String rootPath = request.getContextPath();
    String basePath = request.getScheme() + "://" +
            request.getServerName() + ":" +
            request.getServerPort() + rootPath + "/";
%>

<html>
<head>
    <title>Spring WebSocket</title>
    <meta http-equiv="Expires" content="0"/>
    <meta http-equiv="Cache" content="no-cache"/>
    <meta http-equiv="Pragma" content="no-cache"/>
    <meta http-equiv="Cache-Control" content="no-cache"/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <style type="text/css">
        .msgBox {
            height: 300px;
            width: 800px;
            border: 2px solid #2196F3;
            overflow: auto;
        }
    </style>
    <script type="text/javascript">
        var rootPath = "<%=rootPath%>";
        var basePath = "<%=basePath%>";
        var userId = '${userId}';
        var username = '${username}';
        var clientMark = '${clientMark}';
    </script>
    <script type="text/javascript" src="<%=basePath%>static/js/plugins/jquery/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="<%=basePath%>static/js/common/sockjs.v1.0.0.js"></script>
    <script type="text/javascript" src="<%=basePath%>static/js/common/stomp.v2.3.3.js"></script>
</head>
<body>
    <div>用户id:${userId}</div>
    <div>用户名:${username}</div>
    <div>
        <span>公告:</span><input type="text" name="notice"/>
        <button type="button" id="notice">发送</button>
    </div>
    <div>
        <span>用户id:</span><input type="text" name="userId"/>
        <span>内容:</span><input type="text" name="contents"/>
        <button type="button" id="sendToUser">发送</button>
    </div>
    <div>公告列表:</div>
    <div id="noticeList" class="msgBox"></div>
    <div>消息列表:</div>
    <div id="msgList" class="msgBox"></div>
    <script type="text/javascript" src="<%=basePath%>static/js/springWebsocket/springWebsocket.js"></script>
</body>
</html>

定义JavaScript脚本:

var socket = null;
var stompClient = null;

function closeSocket() {
    if (socket == null || socket.readyState == 2 || socket.readyState == 3) {
        return true;
    }
    socket.close();
}

//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常.
window.onbeforeunload = function () {
    closeSocket();
};

function showMsg(webMsg) {
    switch (webMsg['type']) {
        //公告
        case '1': {
            var noticeHtm = '<div>' + webMsg['contents'] + '</div>';
            $('#noticeList').append(noticeHtm);
            $("#noticeList").scrollTop($("#noticeList")[0].scrollHeight);
            break;
        }
        //点对点发消息
        case '2': {
            var msgHtm = '<div>' + webMsg['contents'] + '</div>';
            $('#msgList').append(msgHtm);
            $("#msgList").scrollTop($("#msgList")[0].scrollHeight);
            break;
        }
        //检查异地登录
        case '3': {
            if (webMsg['clientMark'] != clientMark) {
                closeSocket();
                alert('您的账号在另一处登录');
            }
            break;
        }
        default: {
            alert("WebSocket接收到未知消息...");
            break;
        }
    }
}

function connect() {
    socket = new SockJS(rootPath + '/any-socket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        // 订阅 /topic/to-all 实现公告
        stompClient.subscribe(rootPath + '/topic/to-all', function (dd) {
            showMsg(JSON.parse(dd.body));
        });
        // 订阅 /user/userId/to-one 实现点对点
        stompClient.subscribe(rootPath + '/user/' + userId + '/to-one', function (dd) {
            showMsg(JSON.parse(dd.body));
        });
        var webMsg = {
            'userId': userId,
            'username': username,
            'clientMark': clientMark,
            'type': '3'
        };
        stompClient.send(rootPath + "/app/to-one", {}, JSON.stringify(webMsg));
    });
}

connect();

$(function () {
    $('#notice').on('click', function () {
        if (socket == null) {
            alert('WebSocket连接未打开');
            return true;
        }
        if (socket.readyState == 0) {
            alert('WebSocket正在连接中,请稍后再发送消息');
            return true;
        }
        if (socket.readyState == 2) {
            alert('WebSocket连接正在关闭中,无法发送消息');
            return true;
        }
        if (socket.readyState == 3) {
            alert('WebSocket连接已关闭,无法发送消息');
            return true;
        }
        var webMsg = {
            'contents': $('input[name="notice"]').val(),
            'type': '1'
        };
        stompClient.send(rootPath + "/app/to-all", {}, JSON.stringify(webMsg));
    });
    $('#sendToUser').on('click', function () {
        if (socket == null) {
            alert('WebSocket连接未打开');
            return true;
        }
        if (socket.readyState == 0) {
            alert('WebSocket正在连接中,请稍后再发送消息');
            return true;
        }
        if (socket.readyState == 2) {
            alert('WebSocket连接正在关闭中,无法发送消息');
            return true;
        }
        if (socket.readyState == 3) {
            alert('WebSocket连接已关闭,无法发送消息');
            return true;
        }
        var webMsg = {
            'userId': $('input[name="userId"]').val(),
            'username': username,
            'contents': $('input[name="contents"]').val(),
            'type': '2'
        };
        stompClient.send(rootPath + "/app/to-one", {}, JSON.stringify(webMsg));
    });
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,713评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,563评论 18 139
  • spring官方文档:http://docs.spring.io/spring/docs/current/spri...
    牛马风情阅读 1,638评论 0 3
  • 有的时候你想让一个函数同时是两个类的友元函数。你可以选择把一个类的成员函数作为另一个类的友元函数,但是一般的情况是...
    Stroman阅读 224评论 0 0
  • 今天看《最美的教育最简单》第二章的前三节,作者举了很多高教育水平父母没能教育出他们理想中和他们一样“高水平”的孩子...
    林江影月阅读 582评论 0 2