Spring Boot實現Web Socket
阿新 • • 發佈:2018-12-15
實現程式碼
依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
##啟動類
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
配置
@Configuration
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Bean
public ServerEndpointExporter serverEndpointExporter (){
return new ServerEndpointExporter();
}
}
WebSocket
@ServerEndpoint("/websocket") @Component public class MyWebSocket { private static AtomicLong onlineCount = new AtomicLong(); private static ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session) { webSocketMap.put(session.getId(), session); System.out.println("有新連結加入!當前線上人數為:\t" + onlineCount.incrementAndGet()); } @OnClose public void onClose(Session session) { webSocketMap.remove(session.getId()); System.out.println("有一連結關閉!當前線上人數為:\t" + onlineCount.decrementAndGet()); } @OnMessage public void onMessage(String message, Session session) throws IOException { System.out.println("收到訊息:\t" + message); if (message.contains("#")) { String[] msgMap = message.split("#"); String targetId = msgMap[0]; String msg = String.format("[%s]:\t%s", session.getId(), msgMap[1]); session.getBasicRemote().sendText(message + "[self]"); // 單發訊息 for (Session item : webSocketMap.values()) { if (item.getId().equals(targetId)) { sendMessage(item, msg); } } } else { String msg = String.format("[%s]:\t%s", session.getId(), message); session.getBasicRemote().sendText(msg + "[自己]"); // 群發訊息 for (Session item : webSocketMap.values()) { if (!item.getId().equals(session.getId())) { sendMessage(item, msg); } } } } private void sendMessage(Session session, String message) throws IOException { session.getBasicRemote().sendText(message); } }