【springboot】WebScoket双向通信:

文章目录

        • 一、介绍:
        • 二、案例:
        • 三、使用:
            • 【1】导入WebSocket的maven坐标
            • 【2】导入WebSocket服务端组件WebSocketServer,用于和客户端通信
            • 【3】导入配置类WebSocketConfiguration,注册WebSocket的服务端组件
            • 【4】导入定时任务类WebSocketTask,定时向客户端推送数据
            • 【5】服务实现类:
            • 【6】前端:


一、介绍:

【springboot】WebScoket双向通信:_第1张图片
【springboot】WebScoket双向通信:_第2张图片
【springboot】WebScoket双向通信:_第3张图片

二、案例:

【springboot】WebScoket双向通信:_第4张图片
【springboot】WebScoket双向通信:_第5张图片

三、使用:

【1】导入WebSocket的maven坐标
<dependency>
  <groupId>org.springframework.bootgroupId>
  <artifactId>spring-boot-starter-websocketartifactId>
dependency>

【springboot】WebScoket双向通信:_第6张图片

【2】导入WebSocket服务端组件WebSocketServer,用于和客户端通信
/**
 * WebSocket服务
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {

    //存放会话对象
    private static Map<String, Session> sessionMap = new HashMap();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端:" + sid + "建立连接");
        sessionMap.put(sid, session);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        System.out.println("收到来自客户端:" + sid + "的信息:" + message);
    }

    /**
     * 连接关闭调用的方法
     *
     * @param sid
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
    }

    /**
     * 群发
     *
     * @param message
     */
    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                //服务器向客户端发送消息
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

【springboot】WebScoket双向通信:_第7张图片

【3】导入配置类WebSocketConfiguration,注册WebSocket的服务端组件
/**
 * WebSocket配置类,用于注册WebSocket的Bean
 */
@Configuration
public class WebSocketConfiguration {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

【springboot】WebScoket双向通信:_第8张图片

【4】导入定时任务类WebSocketTask,定时向客户端推送数据
@Component
public class WebSocketTask {
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 通过WebSocket每隔5秒向客户端发送消息
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void sendMessageToClient() {
        webSocketServer.sendToAllClient("这是来自服务端的消息:" + 	DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalDateTime.now()));
    }
}

【springboot】WebScoket双向通信:_第9张图片

【5】服务实现类:
Map map = new HashMap();map.put("type", 1);//通知类型 1来单提醒 2客户催单
map.put("orderId", orders.getId());//订单id
map.put("content","订单号:" + outTradeNo);

webSocketServer.sendToAllClient(JSON.toJSONString(map));

【springboot】WebScoket双向通信:_第10张图片

【6】前端:

【springboot】WebScoket双向通信:_第11张图片
在这里插入图片描述
websocket.html:

DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Demotitle>
head>
<body>
    <input id="text" type="text" />
    <button onclick="send()">发送消息button>
    <button onclick="closeWebSocket()">关闭连接button>
    <div id="message">
    div>
body>
<script type="text/javascript">
    var websocket = null;
    var clientId = Math.random().toString(36).substr(2);

    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        //连接WebSocket节点
        websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);
    }
    else{
        alert('Not support websocket')
    }

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

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

    //接收到消息的回调方法
    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 + '
'
; } //发送消息 function send(){ var message = document.getElementById('text').value; websocket.send(message); } //关闭连接 function closeWebSocket() { websocket.close(); }
script> html>

你可能感兴趣的:(springboot,spring,boot,后端,java)