HTML5   发布时间:2022-04-25  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了HTML5 Server-Sent Events with Java Servlets example大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

1. Introduction to Server-Sent Events

The Server-Sent Events are the new APIs for opening an http connection for receiving push notifications from a server in the form of DOM events. Consider below javascript code:

//...
var eventsource = new Eventsource("/some/data.html");

eventsource.onmessage function(event) {

	alert.data;

};
//...

The above code can be executed in any modern browser (ofcourse the server-side script /some/data.html needs to be implemented first). We create an object of class Eventsource. We pass a server URL which implements Server-sent events protocol. And finally we add a handler function on .onmessage. Every time server sends a message,the handler is called and the event object will have the data.

No need for pooling. The javascript handler will be asynchronously called.

The server needs to specific. First the response content type must be set to text/event-stream. and the data needs to be sent in following format.

...
data: This is some data

data: a quick brown fox

data: jumps over a lazy dog.
...

You got the idea. Lets quickly create a Java Servlet based application with Client code for Server-sent event.

2. Server-Sent Events,Hello World Servlet

For our Hello world example,we create an html page that has a button to start server-sent event. The server will send us a timestamp every second which we just display on page.

index.jsp

<!DOCTYPE HTML>
<html>
<body>
	Time: <span id="foo"></span>
	
	<br>
	<button onclick"start()>Start</button>

	<script type"text/javascript>
	function start({

		"HelloServlet";
		
		eventsource{
		
			document.getElementById'foo'.innerHTML = event;
		
		;
		
	}
	</script</body</html>

In above javascript code we created an event source for “/HelloServlet” path. On each message we just prints the data in span “foo”.

Now lets check Servlet code which sents the Server-Sent Events.

HelloServlet.java

 
 @H_171_197@ 

 
 
@H_944_199@
package net.viralpatel.servlets; import java.io.IOException; .PrintWriterimport javax.servlet.ServletException.http.httpServlet.httpServletrequest.httpServletResponsepublic class TestServlet extends httpServlet { void doGet(httpServletrequest request, httpServletResponse response) throws ServletException:rgb(153, IOException { //content type must be set to text/event-stream responsesetContentType"text/event-stream"; //encoding must be set to UTF-8 responsesetCharacterEncoding"UTF-8"; PrintWriter writer = responsegetWriter; for(int i=0; i<10++{ writerwrite"data: "+ SystemcurrentTimeMillis) +"\n\n"; try { Threadsleep(1000; } catch (InterruptedException e{ eprintStackTrace} } writerclose; } }

The servlet is quite simple. Content type must be set to “text/event-stream” and the character encoding must be UTF-8.

Also each message that we send must ends with \n\n.

web.xml

@H_419_386@<?xml version="1.0" encoding="UTF-8"?>
<web-app "WebApp_ID" version"2.4xmlns"http://java.sun.com/xml/ns/j2eexmlns:xsi"http://www.w3.org/2001/XMLscheR_327_11845@a-instancexsi:scheR_327_11845@aLOCATIOn"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
	<display-name>ServerSentEvent_httpServlet_example</display-name<welcome-file-list>
		<welcome-file>index.jsp</welcome-file</welcome-file-list<servlet>HelloServlet<servlet-name</servlet-name<servlet-class>net.viralpatel.servlets.HelloServlet</servlet-class</servlet<servlet-mapping<url-pattern>/HelloServlet</url-pattern</servlet-mapping>
</web-app>

Output

HTML5 Server-Sent Events with Java Servlets example

source code: https://gist.github.com/viralpatel/7007662

3. Multiple Events in Server-Sent Events

In above example we tracked a single event. The servlet sent only single data entity. In real world,you might want to send a number of events and want to track same on client side.

For example,consider below Javascript snippet.

;


		eventsourceaddEventListener'up_Vote':rgb(153, {
			
				document'up';
				
			:rgb(153, false;

		
		eventsource'down_Vote''down';

In above code we used addEventListener() method of Eventsource to add a handler function. We added handler to event “up_Vote” and “down_Vote”. Whenever any of this event changes,we need to update the count on html page.

The server must send the data in format:

...
event: up_Vote
data: 10

event: down_Vote
data: 5

event: up_Vote
data: 12

event: down_Vote
data: 9

...

The Java Servlet code for this example should be:
HelloServlet.java

writer;
writer Notice single \n in event and double \n\n in data.
You should get following output when the servlet is executed.

HTML5 Server-Sent Events with Java Servlets example

3.1. The Eventsource API

In the examples above we used the onmessage event to get messages. But other events are also available:

Events Description
onopen When a connection to the server is opened
onmessage When a message is received
onerror When an error occurs

4. Browser compatibility

As of Oct 2013 – Internet explorer is your enemy :) Server-sent events are supported in all major browsers (Firefox,Opera,Chrome,Safari.) except for Internet Explorer.

大佬总结

以上是大佬教程为你收集整理的HTML5 Server-Sent Events with Java Servlets example全部内容,希望文章能够帮你解决HTML5 Server-Sent Events with Java Servlets example所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
猜你在找的HTML5相关文章