消息推送springboot+websocket简单demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chen_jia_hao/article/details/82388149

这里为了方便,使用springboot实现。模板引擎使用thymeleaf(默认)。

springboot+websocket demo下载:https://gitee.com/chen_jia_hao/websocket

1、Intellj Idea 创建新的springboot项目。

可参考下面部分截图:

整个demo结构如下所示:

2、配置类,需配置如下,方可使用websocket。

package com.cjh.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @author chen jia hao
 */
@Configuration
public class WebConfig {
    /**
     * 支持websocket
     * 如果不使用内置tomcat,则无需配置
     * @return
     */
    @Bean
    public ServerEndpointExporter createServerEndExporter(){
        return new ServerEndpointExporter();
    }
}

3、websocket服务端处理类(核心)

package com.cjh.websocket.controller;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket服务端
 * @author chen jia hao
 */
@Component
@ServerEndpoint(value = "/myWebSocket")
public class MyWebSocket {

    //用来存放每个客户端对应的MyWebSocket对象
    private static CopyOnWriteArraySet<MyWebSocket> user = new CopyOnWriteArraySet<MyWebSocket>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    @OnMessage
    public void onMessage(String message,Session session) throws IOException {

        //群发消息
        for (MyWebSocket myWebSocket : user) {
            myWebSocket.session.getBasicRemote().sendText(session.getId()+"说:"+message);
            //myWebSocket.session.getBasicRemote().sendText("<img src=''/>");
        }
    }

    @OnOpen
    public void onOpen(Session session){
        System.out.println(session.getId()+" open...");
        this.session = session;
        user.add(this);
    }
    @OnClose
    public void onClose(){
        System.out.println(this.session.getId()+" close...");
        user.remove(this);
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.out.println(this.session.getId()+" error...");
        error.printStackTrace();
    }

}

4、前台界面,聊天测试

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <style>
        #message{
            height: 520px;
            border-bottom: 1px solid gray;
            padding: 20px 30px;
        }
        #container{
            margin: 0 auto;
            width: 720px;
            border: 1px solid gray
        }
        input{
            width: 300px;
            height: 36px;
            border: 1px solid gray;
            background:none;
            outline:none;
        }
        input:focus{
            border-color: yellow;
        }
        button{
            height: 36px;
        }
    </style>
</head>
<body>
<div id="container">
    <div id="message">

    </div>
    <div>
        <input id="text" type="text" placeholder="输入内容..."/>
        <button onclick="send()">发送消息</button>
    </div>
</div>
<script th:inline="javascript" type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/myWebSocket");
    }
    else {
        alert('当前浏览器不支持websocket');
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        var data = event.data;
        document.getElementById('message').innerHTML += data+'<br/>';
    }

    //连接成功建立的回调方法
    websocket.onopen = function () {
        console.log("onopen...");
    }
    //连接关闭的回调方法
    websocket.onclose = function () {
        console.log("onclose...");
    }
    //连接发生错误的回调方法
    websocket.onerror = function () {
        console.log("onerror...");
    };
    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }
    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

</script>
</body>
</html>

6、demo效果图:

猜你喜欢

转载自blog.csdn.net/chen_jia_hao/article/details/82388149