1, first look at the simplest SSE:
Only use the SSE-enabled browser (most), the browser built-in EventSource object, the object by default three seconds to refresh the response data.
HTML code (taken from W3cschool):
<!DOCTYPE HTML><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /></Head><Body><H1>Get server-side update data</H1><DivID= "Result"></Div><Script>if(typeof(EventSource)!=="undefined") {varSource=NewEventSource ("Socket");//parameter for request link Source.onmessage=function(event) {document.getElementById ("result"). InnerHTML+=Event.data+ "<br>"; }; }Else{document.getElementById ("result"). InnerHTML="Sorry, your browser does not support Server-sent events ..."; }</Script></Body></HTML>
Tomcat service-side code:
Public classTestservletextendshttpservlet{protected voidDoget (httpservletrequest req, httpservletresponse Res)throwsIOException {res.setheader ("Content-type", "Text/event-stream;charset=utf-8"); You can also set the Content-type directly, but the encoding must be consistentPrintWriter P=Res.getwriter (); while(true) {Thread.Sleep (1000); P.print ("Data:");//Must start with data: otherwise it will not be p.println ("ABC"); P.println ();//must follow the blank line, otherwise no data, does not trigger onmessage. P.flush (); } } }
This way, you can view the details of EventSource.
Long-polling, Websockets, SSE (server-sent Event), the difference between WebRTC and use