当前位置: 首页 > 科技观察

springboot集成Websocket实现后台主动向前端推送消息的案例

时间:2023-03-16 22:53:22 科技观察

相信手机端有服务端的推送消息,比如一些及时的新闻信息。本文主要实现该功能,仅演示一个基本案例。使用了websocket技术。1.什么是网络套接字?WebSocket协议是一种基于TCP的新型网络协议。它实现了客户端和服务器之间的全双工通信。学过计算机网络的人都知道,既然是全双工,就意味着服务器可以主动向客户端发送信息。这与我们的推送技术或者多人在线聊天的功能不谋而合。为什么不用HTTP协议呢?这是因为HTTP是一种单工通信,通信只能由客户端发起。客户端请求,服务端处理,太麻烦了。于是websocket应运而生。下面我们就直接开始使用Springboot启动集成。以下案例在我自己的电脑上测试成功,大家可以根据自己的功能进行修改。2、集成websocket1,环境配置Idea2018专业版(破解版)Maven4.0.0SpringBoot2.2.2websocket2.1.3jdk1.8下面新建一个普通的Springboot项目。2、添加依赖org.springframework.bootspring-boot-starter-weborg.springframework。启动spring-boot-starter-testtestorg.springframework.bootspring-boot-starter-websocket2.1.3.RELEASE3.在application.properties文件中修改端口号:server.port=80814,新建一个config包,新建WebSocketConfig类1@Configuration2publicclassWebSocketConfig{3@Bean4publicServerEndpointExporterserverEndpointExporter(){5returnnewServerEndpointExporter();6}7}5、新建一个服务包,创建一个WebSocketServer类@ServerEndpoint("/websocket/{sid}")@Componentpublicer=statLogFactory。getLog(WebSocketServer.class);//静态变量,用来记录当前在线连接数,应该设计成线程安全的。privatestaticintonlineCount=0;//concurrent包的线程安全Set,用于存放每个client对应的MyWebSocket对象。privatestaticCopyOnWriteArraySetwebSocketSet=newCopyOnWriteArraySet();//与某个客户端的连接会话需要通过它发送给客户端privateSessionsession;//接收sidprivateStringsid="";/***连接调用成功*/@OnOpenpublicvoidonOpen(Sessionsession,@PathParam("sid")Stringsid){this.session=session;webSocketSet.add(this);//添加设置addOnlineCount();//在线人数加1log的方法。info("有一个新的窗口开始监听:"+sid+",当前在线数为"+getOnlineCount());this.sid=sid;try{sendMessage("连接成功");}catch(IOExceptione){log.error("websocketIOexception");}}/***连接close调用的方法*/@OnClosepublicvoidonClose(){webSocketSet.remove(this);//从集合中删除subOnlineCount();//在线人数减去1log.info("关闭一个连接!当前在线人数为"+getOnlineCount());}/***客户端接收后调用的方法message*@parammessage客户端发送的消息*/@OnMessagepublicvoidonMessage(Stringmessage,Sessionsession){log.info("Receivedmessagefromwindow"+sid+":"+message);//群发消息for(WebSocketServeritem:webSocketSet){try{item.sendMessage(message);}catch(IOExceptione){e.printStackTrace();}}}@OnErrorpublicvoidonError(Sessionsession,Throwableerror){log.error("发生错误");error.printStackTrace();}//实现服务端主动推送publicvoidsendMessage(Stringmessage)throwsIOException{this.session.getBasicRemote().sendText(message);}//海量自定义消息publicstaticvoidsendInfo(Stringmessage,@PathParam("sid")Stringsid)throwsIOException{log.info("Pushmessagetowindow"+sid+",pushcontent:"+message);for(WebSocketServeritem:webSocketSet){try{//这里可以设置只push到这个sid,如果为null则全部pushif(sid==null){item.sendMessage(message);}elseif(item.sid.equals(sid)){item.sendMessage(message);}}catch(IOExceptione){continue;}}}publicstaticsynchronizedintgetOnlineCount(){returnonlineCount;}publicstaticsynchronizedvoidaddOnlineCount(){WebSocketServer.onlineCountvoid++;}publicstaticsynchronize(WebSocketServer.onlineCount--;}6.新建controller包,创建Mycontroller类@ControllerpublicclassMyController{//页面请求@GetMapping("/socket/{cid}")publicModelAndViewsocket(@PathVariableStringcid){ModelAndViewmav=newModelAndView("/socket");mav.addObject("cid",cid);returnmav;}//推送数据接口@ResponseBody@RequestMapping("/socket/push/{cid}")publicStringpushToWeb(@PathVariableStringcid,Stringmessage){try{WebSocketServer.sendInfo(message,cid);}catch(IOExceptione){e.printStackTrace();return"pushfailed";}return"sendsuccessful";}}}7.创建一个新的websocket.html页面现在可以在开发服务器和网页上看到效果了。一般来说,Springboot2+Netty+Websocket的组合是比较常用的。这只是一个基本示例,您可以根据需要进行更改。本文转载自微信公众号“愚公要移山”,可关注下方二维码。转载本文请联系愚公移山公众号。