添加Websocket依赖
< dependency> < groupId> org.springframework.boot</ groupId> < artifactId> spring-boot-starter-websocket</ artifactId>
</ dependency>
根据@ServerEndpoint注解注册Websocket
@Configuration
public class AgentWsConfig { @Bean public ServerEndpointExporter serverEndpointExporter ( ) { return new ServerEndpointExporter ( ) ; } }
创建Websocket注解实现的类@ServerEndpoint注解标记类
@ServerEndpoint ( "/websocket/{sessionId}" )
@Component
@Slf4j
public class AgentWsServerPoint { private static final Map < String , Session > SESSION_MAP = new ConcurrentHashMap < > ( ) ; @OnOpen public void onOpen ( @PathParam ( "sessionId" ) String sessionId, Session session) { SESSION_MAP . put ( sessionId, session) ; log. info ( "WebSocket已打开,会话ID是:{}" , sessionId) ; log. info ( sessionId + "建立了连接" ) ; } @OnMessage public String onMessage ( @PathParam ( value = "sessionId" ) String sessionId, String message, Session session) throws Exception { log. info ( sessionId + ":" + message) ; Session session = SESSION_MAP . get ( sessionId) ; try { session. getBasicRemote ( ) . sendText ( "Hello World!" ) ; log. info ( "消息发送成功" ) ; } catch ( IOException e) { e. printStackTrace ( ) ; log. error ( "消息发送失败" ) ; throw e; } return null ; } @OnClose public void onClose ( @PathParam ( value = "sessionId" ) String sessionId, Session session) throws IOException { if ( SESSION_MAP . containsKey ( sessionId) ) { Session session1 = SESSION_MAP . get ( sessionId) ; session1. close ( ) ; SESSION_MAP . remove ( sessionId) ; } log. info ( "websocket is close ,session id is {}" , sessionId) ; } }