<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
package com.springboot.websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebsocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.springboot.websocket.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
@Component
@ServerEndpoint("/websocket")
public class WebsocketCore {
private Logger logger = LoggerFactory.getLogger(WebsocketCore.class);
Session session = null;
@OnOpen
public void onOpen(Session session) {
System.out.println("新建了一个websocket连接");
this.session = session;
System.out.println("session:"+session.getId());
}
@OnClose
public void onClose(Session session) {
System.out.println("关闭了一个websocket连接");
this.session = session;
System.out.println("session:"+session.getId());
}
@OnMessage
public void onMessage(String message) {
try {
System.out.println("session-"+session.getId());
System.out.println("websocket服务接收到消息:"+message);
this.session.getAsyncRemote().sendText("返回消息:你好!");
}catch (Exception e) {
logger.error("socket发送消息异常", e);
}
}
@OnError
public void onError(Throwable error) {
System.out.println("webSocket发生错误");
logger.error("webSocket发生错误", error);
}
}