赞
踩
- <!-- websocket -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-websocket</artifactId>
- </dependency>
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.socket.server.standard.ServerEndpointExporter;
-
- @Configuration
- public class WebSocketConfig {
-
- /**
- * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
- */
- @Bean
- public ServerEndpointExporter serverEndpointExporter() {
- return new ServerEndpointExporter();
- }
-
- }
- import cn.hutool.json.JSONArray;
- import cn.hutool.json.JSONObject;
- import cn.hutool.json.JSONUtil;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.stereotype.Component;
-
- import javax.websocket.*;
- import javax.websocket.server.PathParam;
- import javax.websocket.server.ServerEndpoint;
- import java.util.Map;
- import java.util.concurrent.ConcurrentHashMap;
-
-
- /**
- * @author websocket服务
- */
- @ServerEndpoint(value = "/imserver/{username}")
- @Component
- public class WebSocketServer {
-
- private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
-
- /**
- * 记录当前在线连接数
- */
- public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
-
- /**
- * 连接建立成功调用的方法
- */
- @OnOpen
- public void onOpen(Session session, @PathParam("username") String username) {
- sessionMap.put(username, session);
- log.info("有新用户加入,username={}, 当前在线人数为:{}", username, sessionMap.size());
- JSONObject result = new JSONObject();
- JSONArray array = new JSONArray();
- result.set("users", array);
- for (Object key : sessionMap.keySet()) {
- JSONObject jsonObject = new JSONObject();
- jsonObject.set("username", key);
- // {"username", "zhang", "username": "admin"}
- array.add(jsonObject);
- }
- // {"users": [{"username": "zhang"},{ "username": "admin"}]}
- sendAllMessage(JSONUtil.toJsonStr
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。