springboot整合websocket

WebSocker是一个保持web客户端与服务器长链接的技术。这样在两者通信过程中如果服务器有消息发送给客户端,就无需等待web客户端发送一个请求了(HTTP协议是请求相应式,如果没有Web客户端的请求,服务器是无法对客户端做相应的)。

单独的部署一个WebSocket服务器很简单,只需要几个注解即可。那么当在Spring项目中如何使用WebSocket呢?也行你会想,没什么不同啊。一样通过WebSocket注解就可以了啊。但我们使用Spring的目的就是通过Spring的容器来管理Bean,将WebSocket独立出来如果WebSocket中需要用到Spring容器中的bean该怎么办?

Spring 提供了两种将WebSocket部署在Spring容器中的方法:

方法一:需要支持springboot长连接配置类和websocket配置类

pom.xml配置类

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

 

长连接配置类

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();
    }
}

2.web  socket配置类

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();
    }

}

3.index页面

<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:8099/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>

 

posted @ 2021-02-24 16:46  iJunHello  阅读(140)  评论(0)    收藏  举报