1.导入websocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.代码文章来源:https://www.toymoban.com/news/detail-507052.html
@ServerEndpoint("/webSocket/{userId}")
@Component
@Slf4j
public class SocketServer {
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 接收userId
*/
private String userId = "";
private static AtomicInteger onlineNum = new AtomicInteger();
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
*/
public static ConcurrentHashMap<String, SocketServer> webSocketMap = new ConcurrentHashMap<>();
static IScreenService screenService;
@OnOpen
public void onOpen(Session session,@PathParam("userId") String userId){
this.session = session;
this.userId = userId;
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
webSocketMap.put(userId, this);
} else {
webSocketMap.put(userId, this);
addOnlineCount();
}
log.info(userId+"加入WebSocket,当前人数为:"+onlineNum);
try {
sendMessage("连接成功!");
// 链接成功以后发送数据
Scheduler scheduler = CronUtil.getScheduler();
boolean started = scheduler.isStarted();
if (!started){
// 支持秒级别定时任务
CronUtil.setMatchSecond(true);
log.info("定时任务开启....");
createSchedule();
CronUtil.start();
}
} catch (Exception e) {
log.error("用户连接异常",e);
}
}
/**
* 定时推送消息
*/
public void createSchedule(){
CronUtil.schedule("*/1 * * * * ?", new Task() {
@Override
public void execute() {
try {
// todo 处理逻辑
} catch (Exception e) {
log.error("日报数据查询异常!");
e.printStackTrace();
}
}
});
}
@OnClose
public void onClose() {
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
//从set中删除
subOnlineCount();
}
log.info("用户退出:" + userId + ",当前在线人数为:" + onlineNum);
}
/**
* 发送信息
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
if(ObjectUtil.isNotNull(session)){
synchronized (session){
session.getBasicRemote().sendText(message);
}
}
}
public static void addOnlineCount(){
onlineNum.incrementAndGet();
}
public static void subOnlineCount() {
onlineNum.decrementAndGet();
}
}
3.配置文章来源地址https://www.toymoban.com/news/detail-507052.html
@Configuration
public class SocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Autowired
public void serScreenService(ScreenServiceImpl screenService){
SocketServer.screenService = screenService;
}
}
到了这里,关于java 使用 websocket的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!