-
引入依赖
<!--websocket--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
-
编写配置类
/** * 开启WebSocket支持 * @author: yww * @createTime: 2021/8/13 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } }
-
编写webSocket服务类
/** * @author: yww * @createTime: 2021/8/13 */ @ServerEndpoint("/ws/{userId}") @Component public class WebSocketServer { private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); /** * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象8 */ private static ConcurrentHashMap<String,WebSocketServer> clients = new ConcurrentHashMap<>(); /** * 与某个客户端的连接会话,需要通过它来给客户端发送数据 */ private Session session; /** * 接收id */ private String userId; /** * 开启连接 * @param userId * @param session */ @OnOpen public void onOpen(@PathParam("userId") String userId, Session session){ log.info("连接建立: "+ userId); this.userId = userId; //判断该id是否已经加入,如果已经加入不重复加入 if(!Share.isEmpty(userId)){ this.session = session; clients.put(userId,this); log.info("现在连接的客户端 用户id为: "+userId); //新建连接,查询该连接用户id未读的消息 /* HashMap<String, Object> map = new HashMap<>(); map.put("userId",userId); map.put("status","0"); sendMessageToUser(userId,nNoticeService.queryList(map));*/ } } /** * 关闭连接 */ @OnClose public void onClose(){ log.info("连接关闭"); } /** * 接收消息 * @param message * @param session */ @OnMessage public void onMessage(String message, Session session){ try{ log.info("接收到消息:"+message+" 用户id为: "+this.userId); Thread.sleep(2000); session.getBasicRemote().sendText("收到了 "+this.userId+" 的消息");//发送消息 }catch (IOException e){ e.printStackTrace(); }catch (InterruptedException e){ e.printStackTrace(); } } /** * 连接错误 * @param session * @param throwable */ @OnError public void onError(Session session,Throwable throwable){ throw new IllegalArgumentException(throwable); } /** * 向所有在线用户发送消息 * @param message */ public static void sendAllMessage(String message){ clients.forEach((k,v) ->{ try { v.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } }); } /** * 向指定用户发送消息 * @param userId * @param message */ public static void sendMessageToUser(String userId,String message){ clients.forEach((k,v) ->{ if(clients.get(userId) == null){ log.error("接收消息对象未上线!!!"); }else{ if(k.equals(userId)){ try { v.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } }); } /** * 向指定用户发送消息 * @param userId * @param object */ public static void sendMessageToUser(String userId,Object object){ clients.forEach((k,v) ->{ if(clients.get(userId) == null){ log.error("接收消息对象未上线!!!"); }else{ if(k.equals(userId)){ try { v.sendMessage(object); } catch (IOException | EncodeException e) { e.printStackTrace(); } } } }); } /** * 发送消息 * @param object * @throws IOException * @throws EncodeException */ public void sendMessage(Object object) throws IOException, EncodeException { //异步发送消息 //this.session.getAsyncRemote().sendObject(object); //同步发送消息 this.session.getBasicRemote().sendObject(object); } /** * 发送消息 * @param message * @throws IOException */ public void sendMessage(String message) throws IOException{ this.session.getBasicRemote().sendText(message); } }
-
前端测试
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro" th:with="unixstamp=${#dates.createNow().time}"> <!--引用头部--> <div th:include="common/common :: common"></div> <head> <meta charset="UTF-8"> <title>websocket测试</title> </head> <body> <div style="text-align: center"> <div id="content"></div> <input type="text" class="msg"/><br/> <input type="button" value="发送" onclick="sendMessage()"/><br/> <input type="button" value="关闭websocket" onclick="sock.close()"/> </div> <!--websocket--> <script> var url=null; var sock=null; var userId = "user001"; // var userName=getQueryString("userName") //百度来的函数,用来截取参数 $(function(){ if(!window.WebSocket){ alert('你的浏览器不支持WebSocket'); }else{ url='ws://localhost:8011/shopping/ws/'+userId sock=new WebSocket(url) sock.onopen=function () { $("#content").append("<h1>欢迎"+userId+"来到聊天室</h1>"); } sock.onmessage=function (e) { $("#content").append("<p>"+e.data+"</p>") } sock.onclose=function () { window.close(); } } }); function sendMessage() { var date=new Date() sock.send(userId+" "+date.toLocaleTimeString()+" 说<br/>"+$('.msg').val()) $('.msg').val("") } </script> </body> </html>
-
向指定用户发送消息
@RequestMapping("/list.html") public String list(){ //向指定用户发送消息 WebSocketServer.sendMessageToUser("1","hello,我 是 admin!"); return "web/websocket/websocketList"; }
SpringBoot整合WebSocket
最新推荐文章于 2024-05-23 10:50:00 发布