实战springboot2.0+webSocket

博客介绍了WebSocket的配置与使用。首先需引入pom文件,接着配置WebSocket并定义服务端。前端和后端建立链接时,本地测试要下载三个JS文件。最后可通过访问指定网址进行测试。
  1. 引入pom文件
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
	<version>2.0.4.RELEASE</version>
</dependency>

2.配置webSocket

 /**
 * @Description 开启WebSocket支持
 * @ClassName WebSocketConfig 
 * @Author kevin
 * @Date 2019/7/11 10:14
 * @Version 1.0
 **/
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
  1. 定义webSocket的服务端
/**
 * @Description TODO
 * @ClassName WebSocket
 * @Author kevin
 * @Date 2019/7/11 10:14
 * @Version 1.0
 **/
@ServerEndpoint("/monitor/webSocket")
@Component
@Slf4j
public class WebSocket {

    /**
     * 全局链接数
     */
    private static int onlineCount = 0;

    /**
     * 保存连接用户
     */
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();

    private Session session;

    /**
     * 建立链接触发
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        log.info("-----------websocket建立连接------当前链接数:{}---", JSONObject.toJSONString(getOnlineCount()));
    }

    /**
     * 断开链接触发
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("-----------websocket断开连接------当前链接数:{}---", JSONObject.toJSONString(getOnlineCount()));
    }

    /**
     * 接收来自客户端的消息
     *
     * @param message 接收消息
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("-----------websocket收到来自客户端的消息:{}---------", message);
        // 将收到的消息群发给所有在线
        webSocketSet.forEach(item -> {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 发生错误时触发
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务器主动推送
     *
     * @param message
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public void sendInfo(JSONObject message) throws IOException {
        log.info("推送消息到推送内容:" + message);
        webSocketSet.forEach(item -> {
            try {
                item.sendMessage(message.toJSONString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }

    /**
     * 移除链接
     */
    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

    /**
     * 获取链接数
     *
     * @return
     */
    public static synchronized int getOnlineCount() {
        return WebSocket.onlineCount;
    }

    /**
     * 添加链接数
     */
    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

}
  • 前端和后端建立链接(本地测试请下载jquery-3.4.1.min.js、sockjs.js、stomp.min.js三个JS)
<!DOCTYPE HTML>
<html>
<head>
    <title>kevin  WebSocket  Test</title>
</head>

<body>
Welcome<br/>
<input id="text" type="text" /><button οnclick="send()">Send</button>    <button οnclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
   		 // 与服务端创建的连接
        websocket = new WebSocket("ws://localhost:8880/monitor/webSocket");
    }
    else{
    // 浏览器不支持webSocket时使用SockJS
   websocket  = new SockJS("http://127.0.0.1:8080/my/socket");
       //  alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }

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

    //连接关闭的回调方法
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }

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

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }

    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

访问:http://127.0.0.1:8880/index.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值