当前位置: 首页>后端>正文

WebSocket快速体验 - Spring Boot & JavaScript

公司最近的项目需要用到WebSocket实现消息的适时推送,比如预警消息等,本文使用Spring Boot和JavaScript实现了快速demo

Websocket服务端 - Spring Boot

  • 引入依赖: pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  • Websocket配置
@EnableWebSocket
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
  • Websocket消息处理
    监听事件open、message、close、error
@Slf4j
@Component
@ServerEndpoint(value = "/websocket")
@EnableScheduling
public class WebsocketHandler {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocket connection opened: " + session.getId());
        sessionSet.add(session);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("Received message from client: " + message);
        session.getBasicRemote().sendText("Hello, WebSocket client!");
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        System.out.println("WebSocket connection closed: " + session.getId() + ", Reason: " + reason.getReasonPhrase());
        sessionSet.remove(session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.err.println("Error occurred on WebSocket connection: " + session.getId());
        error.printStackTrace();
    }
}

WebSocket客户端 - JavaScript

//创建WebSocket
var socket = new WebSocket("ws://localhost:8080/websocket");

//监听消息
socket.onmessage = function(event) {
    if (typeof event.data === 'string') {
        // 接收到文本消息的处理逻辑
        console.log("Received text message from server: " + event.data);
    } else if (event.data instanceof Blob) {
        // 接收到二进制数据的处理逻辑
        var reader = new FileReader();
        reader.onload = function() {
            var binaryData = reader.result;
            console.log("Received binary data from server: " + binaryData);
        };
        reader.readAsArrayBuffer(event.data);
    } else {
        console.log("Received message from server: " + event.data);
    }
};

//发送消息给服务器
socket.send("hello world");

参考

  • 【websocket】spring boot 集成 websocket 的四种方式

https://www.xamrdz.com/backend/3y41940671.html

相关文章: