原文链接:https://www.dubby.cn/detail.html?id=9102
实现代码
依赖
<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);
}
}
Github地址
https://github.com/dubby1994/web-socket
网友评论