赞
踩
1、在pom.xml中添加依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
2、创建WebSocket配置类(WebSocketConfig.java )
package com.jeff.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * * @description: WebSocket配置 * @author: Jeff * @date: 2019年12月12日 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { System.out.println("SpringBoot 注册 WebSocket"); return new ServerEndpointExporter(); } }
3、创建ws协议的Controller(WebSocketFloorServer.java)
package com.jeff.controller; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeUnit; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component; @Component @ServerEndpoint("/websocket/{floorId}/floor.do") public class WebSocketFloorServer { // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象 private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<>(); private static final String FLOOR_ID = "floorId"; /** * * @description: 连接建立成功调用的方法 * @author: Jeff * @date: 2019年12月12日 * @param floorId 楼层id * @param session 与某个客户端的连接会话,需要通过它来给客户端发送数据 */ @OnOpen public void onOpen(@PathParam("floorId") String floorId, Session session) { // session 最大空闲时间为10分钟。 session.setMaxIdleTimeout(TimeUnit.MINUTES.toMillis(10)); session.getUserProperties().put(FLOOR_ID, floorId); webSocketSet.add(session); // 加入set中 System.out.println("楼层:" + floorId + "新建连接,当前连接数为:" + getOnlineCount()); } /** * * @description: 连接关闭调用的方法 * @author: Jeff * @date: 2019年12月12日 * @param session */ @OnClose public void onClose(Session session) { String floorId = (String) session.getUserProperties().get(FLOOR_ID); webSocketSet.remove(session); // 从set中删除 System.out.println("楼层:" + floorId + "关闭连接,当前连接数为:" + getOnlineCount()); } /** * * @description: 收到客户端消息后调用的方法 * @author: Jeff * @date: 2019年12月12日 * @param message 客户端发送过来的消息 * @param session */ @OnMessage public void onMessage(String message, Session session) { if (webSocketSet.contains(session)) { String floorId = (String) session.getUserProperties().get(FLOOR_ID); System.out.println("楼层:" + floorId + " 的消息:" + message); } } /** * * @description: 通过楼层id发送消息 * @author: Jeff * @date: 2019年12月12日 * @param message * @param floorId */ public void sendMessage(String message, String floorId) { if (getOnlineCount() != 0) { try { for (Session item : webSocketSet) { if (floorId.equals(item.getUserProperties().get(FLOOR_ID))) { item.getBasicRemote().sendText(message); System.out.println("发送消息:" + message); } } } catch (Exception e) { System.out.println(e.getMessage()); } } } public int getOnlineCount() { return webSocketSet.size(); } }
4、创建测试controller(FloorController.java)
package com.jeff.controller; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; @RestController @RequestMapping("floor") public class FloorController { @Autowired private WebSocketFloorServer socketFloorServer; @RequestMapping("hello") public String hello(String floorId) { Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "Jeff"); map.put("age", 18); map.put("currentDate", new Date()); socketFloorServer.sendMessage(JSONObject.toJSONString(map), floorId); return "HelloWord"; } }
5、打开websocket测试工具连接
6、打开浏览器测试,访问 http://localhost:8080/floor/hello?floorId=1
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。