项目总结48:Springboot集成Websocket案例
Springboot集成Websocket的具体实现由很多方式,但原理是一样的;
先放一个具体的案例:
方案1
pom.xml jar依赖
<!-- websocket --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
服务端发送消息
package com.hs.web.thirdparty.webconnect; import com.hs.common.util.json.JsonUtil; import java.util.ArrayList; import java.util.List; public class WebConnectionManager { private static WebConnectionManager instance = new WebConnectionManager(); private List<UpdateListener> changeListenerList; private WebConnectionManager() { changeListenerList = new ArrayList<UpdateListener>(); } public static WebConnectionManager getInstance() { return instance; } public void addChangeListener(UpdateListener changeListener) { synchronized (changeListenerList) { changeListenerList.add(changeListener); } } public void removeChangeListener(UpdateListener changeListener) { synchronized (changeListenerList) { for (UpdateListener listener : changeListenerList) { if (listener.getUid().equals(changeListener.getUid())) { changeListenerList.remove(listener); break; } } } } public void sendMessage(String message) { synchronized (changeListenerList) { for (UpdateListener listener : changeListenerList) { listener.updateHandle(message); } } } public void sendMessage(Object obj) { //System.out.println("JsonUtil.toJson(obj): " +JsonUtil.toJson(obj)); sendMessage(JsonUtil.toJson(obj)); } private String getMessage() { return null; } public static void main(String[] args) { } }
客户端请求入口
package com.hs.web.thirdparty.webconnect; import org.springframework.stereotype.Component; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.logging.Logger; @ServerEndpoint(value = "/monitor") @Component public class WebSocketServer { private Session targetSession; private UpdateListener changeListener; private static final Logger sysLogger = Logger.getLogger("sysLog"); /** *@Description:链接建立成功时调用的方法 *@param *@return void *@author TangYujie *@date 2019/12/12 17:11 */ @OnOpen public void open(Session session) { this.targetSession = session; changeListener = new UpdateListener() { @Override public String getUid() { return targetSession.getId(); } @Override public void updateHandle(String message) { sendMessage(message); } }; WebConnectionManager.getInstance().addChangeListener(changeListener); sysLogger.info("*** WebSocket opened from sessionId " + targetSession.getId()); } /** *@Description:收到客户端消息 *@param *@return void *@author TangYujie *@date 2019/12/12 17:13 */ @OnMessage public void inMessage(String message) { } /** *@Description: 连接关闭 *@param *@return void *@author TangYujie *@date 2019/12/12 17:15 */ @OnClose public void end() { WebConnectionManager.getInstance().removeChangeListener(changeListener); sysLogger.info("*** WebSocket closed from sessionId " + this.targetSession.getId()); } private synchronized void sendMessage(String message){ try { targetSession.getBasicRemote().sendText(message); } catch (IOException e) { sysLogger.warning(e.getMessage()); } catch(IllegalStateException e){ sysLogger.warning(e.getMessage()); } } }
监听接口类:一个接口类,定义了updateHandle(数据库处理)和getUid(获取Uid)两个方法
package com.hs.web.thirdparty.webconnect; public interface UpdateListener { void updateHandle(String message); String getUid(); }
服务端发送消息
public static void main(String[] args) { String data = "this is a test message"; WebConnectionManager.getInstance().sendMessage(data); }
分析说明:
1-当客户端通过ws://ip:port/monitor连接socket时,根据@ServerEndpoint(value = "/monitor")注解;执行WebSocketServer 标有@OnOpen的open方法,即建立一个连接;
2-open方法中会实现一个UpdateListener 接口类,并将该实现加入到WebConnectionManager 中的List<UpdateListener> changeListenerList中;而UpdateListener 接口类中的updateHandle实现了targetSession.getBasicRemote().sendText(message);即服务端的消息推送;
3-当服务端通过WebConnectionManager.getInstance().sendMessage(data)发送消息时,会遍历List<UpdateListener> changeListenerList,执行其中的updateHandle方法,从而进行消息推送;
方案2,参考资料
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
开启WebSocket支持(tomcat启动,不需要本类)
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * 开启WebSocket支持(tomcat启动,不需要本类) * */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
WebSocketServer
package com.softdev.system.demo.config; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Component; import cn.hutool.log.Log; import cn.hutool.log.LogFactory; /** * @author zhengkai.blog.csdn.net */ @ServerEndpoint("/imserver/{userId}") @Component public class WebSocketServer { static Log log=LogFactory.get(WebSocketServer.class); /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/ private static int onlineCount = 0; /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/ private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>(); /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/ private Session session; /**接收userId*/ private String userId=""; /** * 连接建立成功调用的方法*/ @OnOpen public void onOpen(Session session,@PathParam("userId") String userId) { this.session = session; this.userId=userId; if(webSocketMap.containsKey(userId)){ webSocketMap.remove(userId); webSocketMap.put(userId,this); //加入set中 }else{ webSocketMap.put(userId,this); //加入set中 addOnlineCount(); //在线数加1 } log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount()); try { sendMessage("连接成功"); } catch (IOException e) { log.error("用户:"+userId+",网络异常!!!!!!"); } } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { if(webSocketMap.containsKey(userId)){ webSocketMap.remove(userId); //从set中删除 subOnlineCount(); } log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息*/ @OnMessage public void onMessage(String message, Session session) { log.info("用户消息:"+userId+",报文:"+message); //可以群发消息 //消息保存到数据库、redis if(StringUtils.isNotBlank(message)){ try { //解析发送的报文 JSONObject jsonObject = JSON.parseObject(message); //追加发送人(防止串改) jsonObject.put("fromUserId",this.userId); String toUserId=jsonObject.getString("toUserId"); //传送给对应toUserId用户的websocket if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){ webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString()); }else{ log.error("请求的userId:"+toUserId+"不在该服务器上"); //否则不在这个服务器上,发送到mysql或者redis } }catch (Exception e){ e.printStackTrace(); } } } /** * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("用户错误:"+this.userId+",原因:"+error.getMessage()); error.printStackTrace(); } /** * 实现服务器主动推送 */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 发送自定义消息 * */ public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException { log.info("发送消息到:"+userId+",报文:"+message); if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){ webSocketMap.get(userId).sendMessage(message); }else{ log.error("用户"+userId+",不在线!"); } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }
服务端发送数据
import com.softdev.system.demo.config.WebSocketServer; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import java.io.IOException; /** * WebSocketController * @author zhengkai.blog.csdn.net */ @RestController public class DemoController { @GetMapping("index") public ResponseEntity<String> index(){ return ResponseEntity.ok("请求成功"); } @GetMapping("page") public ModelAndView page(){ return new ModelAndView("websocket"); } @RequestMapping("/push/{toUserId}") public ResponseEntity<String> pushToWeb(String message, @PathVariable String toUserId) throws IOException { WebSocketServer.sendInfo(message,toUserId); return ResponseEntity.ok("MSG SEND SUCCESS"); } }
页面请求
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>websocket通讯</title> </head> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> var socket; function openSocket() { if(typeof(WebSocket) == "undefined") { console.log("您的浏览器不支持WebSocket"); }else{ console.log("您的浏览器支持WebSocket"); //实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接 //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25"); //var socketUrl="${request.contextPath}/im/"+$("#userId").val(); var socketUrl="http://localhost:9999/demo/imserver/"+$("#userId").val(); socketUrl=socketUrl.replace("https","ws").replace("http","ws"); console.log(socketUrl); if(socket!=null){ socket.close(); socket=null; } socket = new WebSocket(socketUrl); //打开事件 socket.onopen = function() { console.log("websocket已打开"); //socket.send("这是来自客户端的消息" + location.href + new Date()); }; //获得消息事件 socket.onmessage = function(msg) { console.log(msg.data); //发现消息进入 开始处理前端触发逻辑 }; //关闭事件 socket.onclose = function() { console.log("websocket已关闭"); }; //发生了错误事件 socket.onerror = function() { console.log("websocket发生了错误"); } } } function sendMessage() { if(typeof(WebSocket) == "undefined") { console.log("您的浏览器不支持WebSocket"); }else { console.log("您的浏览器支持WebSocket"); console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}'); socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}'); } } </script> <body> <p>【userId】:<div><input id="userId" name="userId" type="text" value="10"></div> <p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="20"></div> <p>【toUserId】:<div><input id="contentText" name="contentText" type="text" value="hello websocket"></div> <p>【操作】:<div><a onclick="openSocket()">开启socket</a></div> <p>【操作】:<div><a onclick="sendMessage()">发送消息</a></div> </body> </html>
心跳检测和重连机制:
- 每隔一段指定的时间(计时器),向服务器发送一个数据,服务器收到数据后再发送给客户端,正常情况下客户端通过onmessage事件是能监听到服务器返回的数据的,说明请求正常。
- 如果再这个指定时间内,客户端没有收到服务器端返回的响应消息,就判定连接断开了,使用websocket.close关闭连接。
- 这个关闭连接的动作可以通过onclose事件监听到,因此在 onclose 事件内,我们可以调用reconnect事件进行重连操作。
END