好了,大略的理解一下,我们来看看springboot+websocket实现推送的过程,以下是个大略的demo。
搭建过程首先我们初始化一个spring boot项目,大家可以根据自己的习气辞官网下载或者用idea来天生,这里我不多说,紧张的是引入websocket依赖,如下图;websocket依赖
@Componentpublic class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}
编写websocket推送做事端
@Component@ServerEndpoint(value = "/websocket/logging")public class LoggingWSServer { private static final Logger LOGGER = LoggerFactory.getLogger(LoggingWSServer.class); private static Map<String, Session> sessionMap = new ConcurrentHashMap<>(); private static Gson gson = new Gson(); private static Map<String,Object> map = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session) { new Thread(() -> {// 这里大家可以根据业务来优化,利用线程池等手段 while(sessionMap.get(session.getId()) != null) { try { List<AaaServer> list = aaaServerService.findList(); if(session.isOpen()) { send(session, gson.toJson(list)); } Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } @OnClose public void onClose(Session session) { sessionMap.remove(session.getId()); LOGGER.info("session断开连接:{}" , session.getId()); } @OnMessage public void onMessage(String message,Session session) { LOGGER.info("收到客户真个:{}",message); map.put("ret",message); send(session,gson.toJson(map)); } private void send(Session session, String toJson) { try { session.getBasicRemote().sendText(toJson); } catch (IOException e) { LOGGER.error("发送缺点:{}",e.getMessage()); } } }
做事端api阐明:

//websocket工具 var websocket = null; //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { //动态获取域名或ip var hostname = window.location.hostname; port = window.location.port; websocket = new WebSocket("ws://"+hostname+":" + port + "/websocket/logging"); } else { console.error("不支持WebSocket"); } //连接发生缺点的回调方法 websocket.onerror = function (e) { console.error("WebSocket连接发生缺点" + e); }; //连接成功建立的回调方法 websocket.onopen = function () { console.log("WebSocket连接成功") }; //吸收到的回调方法 websocket.onmessage = function (event) { console.log("数据是:", event.data ); var data = JSON.parse(event.data); if (data.push) { // 内容 var temp = template('tpl_data',{data : data.push}); console.log("模板==" + temp); document.getElementById("tb").innerHTML = temp; } if(data.ret) { console.log(data.ret) alert(data.ret); } } //发送 $('#send').click(function () { websocket.send($('#sMsg').val()); });
前端页面把稳:
编写的时候一定要把稳一个地方,便是new WebSocket 的地址,一定要和做事端推送的那个地址相同,不然的话,这里吸收不到推送过来的数据。其余,有些浏览器可能不支持websocket,也没紧要,可以利用sockjs或者stomp.js,这是基于websocket的上层协议,大家可以自行去理解以下。不过要把稳,sockjs 处理的url是http或者https,不在因此ws开头的。结语本日就大略的先容到这里,有须要这个demo的,可以关注一下小编,后续小编会把代码上传到gitee,https://gitee.com/bigqianqian/springboot-websocket,可以理解下。下篇文章小编将会先容websocket点对点推送和广播,喜好的朋友点个关注呗[奋斗][奋斗][奋斗],也可以动动手评论下,留下你的理解,小编与你共同发展!