引入websocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置websocket
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpoint() {
return new ServerEndpointExporter();
}
}
websocket核心代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint("/socket")
public class WebSocketServer {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
private ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap(8);
/**
* 连接成功
* @param session
*/
@OnOpen
public void onOpen(Session session) {
sessionMap.put(session.getId(), session);
String queryString = session.getQueryString();
LOGGER.info("session id is {}", session.getId());
LOGGER.info("queryString is {}", queryString);
LOGGER.info("setup connection success userId is {}", session.getId());
try {
sendMessage(session, "cxk");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 连接关闭
*
* @param session
*/
@OnClose
public void onClose(Session session) {
System.out.println("连接关闭");
}
/**
* 接收到消息
*
* @param text
*/
@OnMessage
public void onMsg(String text, Session session) throws IOException {
LOGGER.info("get message {}", text);
}
/**
* 实现服务器主动推送
*/
public void sendMessage(Session session, String message) throws IOException {
session.getBasicRemote().sendText(message);
}
@OnError
public void onError(Session session, Throwable throwable) {
LOGGER.error("get error");
}
}
react 前端部分代码
import React, {useEffect, useState} from 'react';
// 这里不要使用 import 或者 require 引入,否则报错
useEffect(() => {
const webSocket: WebSocket = new WebSocket('ws://localhost:8777/socket')
webSocket.onopen = () => {
console.log('ws onopen');
webSocket.send('from client: hello');
};
webSocket.onmessage = (e) => {
console.log('ws onmessage');
console.log('from server: ' + e.data);
};
}, [])