WebSocket快速体验 - Spring Boot & Ja

2023-06-15  本文已影响0人  十毛tenmao

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

Websocket服务端 - Spring Boot

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@EnableWebSocket
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
@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");

参考

上一篇 下一篇

猜你喜欢

热点阅读