Long-polling, Websockets, SSE (server-sent Event), the difference between WebRTC and use

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.