简介:在springboot中使用websocket
1、引入依赖
java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、创建ServerEndpoint服务
java
@ServerEndpoint(value = "/websocket/team")
@Component
public class MyWebSocketHandler {
//保存所有在线socket连接
private static Map<String, MyWebSocketHandler> webSocketMap = new LinkedHashMap<>();
//记录当前在线数目
private static int count = 0;
//当前连接(每个websocket连入都会创建一个MyWebSocket实例
private Session session;
//处理连接建立
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketMap.put(session.getId(), this);
addCount();
}
//接受消息
@OnMessage
public void onMessage(String message, Session session) {
//从上下中获取对象 无法通过注解获取,因为websocket中会报空指针异常
ApplicationContext context = ApplicationContextRegister.getApplicationContext();
//将string转成JSON对象
JSONObject entries = JSONUtil.parseObj(message);
//将JSON对象转成bean对象
WebsocketJson websocketJson = entries.toBean(WebsocketJson.class);
switch (websocketJson.getType()) {
case "1": {
//创建房间
BankFacadeServiceImpl facadeService = context.getBean(BankFacadeServiceImpl.class);
//业务逻辑
break;
}
case "2": {
//加入队伍
websocketJson.setSessionId(session.getId());
BankFacadeServiceImpl facadeService = context.getBean(BankFacadeServiceImpl.class);
//业务逻辑
break;
}
case "3": {
//退出队伍
websocketJson.setSessionId(session.getId());
BankFacadeServiceImpl facadeService = context.getBean(BankFacadeServiceImpl.class);
//业务逻辑
break;
}
case "4": {
//创建试卷
BankFacadeServiceImpl facadeService = context.getBean(BankFacadeServiceImpl.class);
//业务逻辑
break;
}
case "5": {
//业务逻辑
break;
}
case "6": {
//业务逻辑
break;
}
case "7":{
try {
sendMessage("心跳检测");
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
}
}
}
//处理错误
@OnError
public void onError(Throwable error, Session session) {
// log.info("发生错误{},{}",session.getId(),error.getMessage());
}
//处理连接关闭
@OnClose
public void onClose() {
webSocketMap.remove(this.session.getId());
reduceCount();
}
//组队消息
public void sendMessageJson(WebsocketJson message, MyWebSocketHandler handler) {
try {
if (handler == null) {
this.session.getBasicRemote().sendText(JSONUtil.toJsonStr(JSONUtil.parse(message)));
} else {
handler.sendMessage(JSONUtil.toJsonStr(JSONUtil.parse(message)));
}
} catch (IOException e) {
System.out.println(e.getMessage());
throw new RuntimeException(e);
}
}
//发送消息
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
//广播消息
public static void broadcast() {
MyWebSocketHandler.webSocketMap.forEach((k, v) -> {
try {
v.sendMessage("这是一条测试广播");
} catch (Exception e) {
}
});
}
//操作count,使用synchronized确保线程安全
public static synchronized void addCount() {
MyWebSocketHandler.count++;
}
public static synchronized void reduceCount() {
MyWebSocketHandler.count--;
}
}