1. 服务端编码
@GetMapping(path = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public SseEmitter sse() throws Exception { final SseEmitter emitter = new SseEmitter(); final AtomicInteger i = new AtomicInteger(0); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1 * 1000); emitter.send(i.addAndGet(1)); } catch (InterruptedException e) { throw new UnsupportedOperationException("Not yet implemented!"); } catch (IOException e) { throw new UnsupportedOperationException("Not yet implemented!"); } } } }).start(); return emitter; }
2. 客户端编码
$(function () { var source = new EventSource("/sse"); source.onmessage = function (event) { $('#result').html(event.data); }; });
EventSource为客户端脚本的JavaScript对象