方案
- 短轮询
- 长轮询: 可以使用 Spring 提供的
DeferredResult
实现
- iframe流
- SSE: 服务器响应
text/event-stream
类型的数据流信息,思路类似于在线视频播放
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <script> let source = null; let userId = 7777 if (window.EventSource) { source = new EventSource('http://localhost:7777/sse/sub/'+userId); setMessageInnerHTML("连接用户=" + userId);
source.addEventListener('open', function (e) { setMessageInnerHTML("建立连接。。。"); }, false);
source.addEventListener('message', function (e) { setMessageInnerHTML(e.data); }); } else { setMessageInnerHTML("你的浏览器不支持SSE"); } </script>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| private static Map<String, SseEmitter> sseEmitterMap = new ConcurrentHashMap<>();
public static SseEmitter connect(String userId) { try { SseEmitter sseEmitter = new SseEmitter(0L); sseEmitter.onCompletion(completionCallBack(userId)); sseEmitter.onError(errorCallBack(userId)); sseEmitter.onTimeout(timeoutCallBack(userId)); sseEmitterMap.put(userId, sseEmitter); count.getAndIncrement(); return sseEmitter; } catch (Exception e) { log.info("创建新的sse连接异常,当前用户:{}", userId); } return null; }
public static void sendMessage(String userId, String message) {
if (sseEmitterMap.containsKey(userId)) { try { sseEmitterMap.get(userId).send(message); } catch (IOException e) { log.error("用户[{}]推送异常:{}", userId, e.getMessage()); removeUser(userId); } } }
|
- MQTT
- WebSocket
转载地址: https://mp.weixin.qq.com/s/DlW5XnpG7v0eIiIz9XzDvg