springboot实现websocket
导入pom包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置类
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();
}
}
@Component
@ServerEndpoint(value = "/wsdemo")
@Log
public class MyWebsocket {
private Session session;
private HashMap<String,Session> maps = new HashMap<>();
@OnOpen
public void onOpen(Session session) {
log.info(session.getId()+"已连接");
this.session = session;
maps.put(session.getId(),session);
}
@OnClose
public void onClose() {
maps.remove(this.session.getId());
log.info(this.session.getId()+"退出");
}
@OnMessage
public void onMessage(String message,Session session){
log.info(session.getId()+":"+message);
this.session = session;
sendMessage(message);
}
@SneakyThrows //lombok 减轻异书写方式的操作
public void sendMessage(String message) {
//给自己发送消息
this.session.getBasicRemote().sendText(message);
//给某人发送就获取session执行发送
maps.get("xx").getBasicRemote().sendText(message);
}
}
}
可以自行测试上websocket测试网站上测试