1.引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 与websocket冲突 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<!-- websocket -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.配置类
@Configuration
public class WebsocketConfig {
/**
* 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.websocket监听类
@Slf4j
@ServerEndpoint(value = "/cre-data-manager-factory/factory/socket")
@Component
public class FactorySocket {
/** 记录当前在线连接数 */
public static AtomicInteger onlineCount = new AtomicInteger(0);
/** 存放已经连接的session */
public static Map<String,Session> sessionMap = new ConcurrentHashMap();
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) throws IOException {
// websocket鉴权
if (StringUtils.isEmpty(session.getQueryString()) || !session.getQueryString().contains("8dd2d7e7b0b54637")){
log.info("websocket鉴权失败");
session.close();
return;
}
log.info(JSON.toJSONString(session.getRequestParameterMap()));
onlineCount.incrementAndGet(); // 在线数加1
sessionMap.put(session.getId(),session);
log.info("有新连接加入:{},当前连接数为:{}", session.getId(), onlineCount.get());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
onlineCount.decrementAndGet(); // 在线数减1
sessionMap.remove(session.getId());
log.info("有一连接关闭:{},当前连接数为:{}", session.getId(), onlineCount.get());
}
/**
* 收到客户端消息后调用的方法
*
* @param message
* 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
this.sendMessage("成功收到消息: " + message, session);
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 服务端发送消息给客户端
*/
public void sendMessage(String message, Session toSession) {
try {
log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
toSession.getAsyncRemote().sendText(message);
} catch (Exception e) {
log.error("服务端发送消息给客户端失败:{}", e);
}
}
}
ws://localhost:8217/cre-data-manager-factory/factory/socket 根据这样的请求串就可以连接socket