Commits

Micha Kops committed 98d43ee Draft

Initial import. Examples using nodejs and jetty added.

  • Participants

Comments (0)

Files changed (8)

+.project
+.settings
+target
+.classpath
+bin
+# HTML5 Server Send Events using Node.js or Jetty
+
+A short example for the W3C working draft implementation on server side events.
+
+You're able to run the examples using *node.js* or *Maven* with Jetty:
+
+## Node.js
+
+Simply run the following command:
+
+    node server.js
+
+Afterwards just open the following URL in your browser: [http://localhost:8080/]
+
+
+## Maven + Jetty
+
+You need to have [Maven] installed - then simply run the following goal:
+
+    mvn jetty:run
+
+Again you're able to see the results when opening [http://localhost:8080/] in your browser.
+
+## Tutorial
+
+Please feel free to take a look at the full tutorial on my blog at [www.hascode.com]. 
+
+---
+
+**2012 Micha Kops / hasCode.com**
+
+  [http://localhost:8080/]:http://localhost:8080/
+  [Maven]:http://maven.apache.org
+  [www.hascode.com]:http://www.hascode.com/
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8" />
+</head>
+<body>
+	<input type="button" id="stopButton" value="Stop Listening"/>
+	<hr/>
+	<div id="content"></div>
+	<script>
+    var source = new EventSource('/talk');
+    source.addEventListener('open', function(e) {
+    	  document.getElementById('content').innerHTML += 'Connections to the server established..<br/>';
+    }, false);
+    source.onmessage = function(e) {
+      document.getElementById('content').innerHTML += e.data + '<br/>';
+    };
+    document.getElementById('stopButton').onclick=function(){
+    	document.getElementById('content').innerHTML += 'Listening to server events stopped..<br/>';
+    	source.close();
+    }
+  </script>
+</body>
+</html>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+	<groupId>com.hascode.tutorial</groupId>
+	<artifactId>html5-server-send-events</artifactId>
+	<version>0.0.1</version>
+	<dependencies>
+		<dependency>
+			<groupId>org.eclipse.jetty</groupId>
+			<artifactId>jetty-eventsource-servlet</artifactId>
+			<version>1.0.0</version>
+		</dependency>
+		<dependency>
+			<groupId>javax.servlet</groupId>
+			<artifactId>javax.servlet-api</artifactId>
+			<version>3.0.1</version>
+		</dependency>
+	</dependencies>
+
+	<build>
+		<plugins>
+			<plugin>
+				<groupId>org.mortbay.jetty</groupId>
+				<artifactId>jetty-maven-plugin</artifactId>
+				<version>8.1.7.v20120910</version>
+			</plugin>
+		</plugins>
+	</build>
+</project>
+var http = require('http');
+var fs = require('fs');
+
+/*
+ * send interval in millis
+ */
+var sendInterval = 5000;
+
+function sendServerSendEvent(req, res) {
+	res.writeHead(200, {
+		'Content-Type' : 'text/event-stream',
+		'Cache-Control' : 'no-cache',
+		'Connection' : 'keep-alive'
+	});
+
+	var sseId = (new Date()).toLocaleTimeString();
+
+	setInterval(function() {
+		writeServerSendEvent(res, sseId, (new Date()).toLocaleTimeString());
+	}, sendInterval);
+
+	writeServerSendEvent(res, sseId, (new Date()).toLocaleTimeString());
+}
+
+function writeServerSendEvent(res, sseId, data) {
+	res.write('id: ' + sseId + '\n');
+	res.write("data: new server event " + data + '\n\n');
+}
+
+http.createServer(function(req, res) {
+	if (req.headers.accept && req.headers.accept == 'text/event-stream') {
+		if (req.url == '/talk') {
+			sendServerSendEvent(req, res);
+		} else {
+			res.writeHead(404);
+			res.end();
+		}
+	} else {
+		res.writeHead(200, {
+			'Content-Type' : 'text/html'
+		});
+		res.write(fs.readFileSync(__dirname + '/index.html'));
+		res.end();
+	}
+}).listen(8080);
+
+
+

src/main/java/com/hascode/tutorial/MySSEServlet.java

+package com.hascode.tutorial;
+
+import java.io.IOException;
+import java.util.Date;
+
+import javax.servlet.annotation.WebInitParam;
+import javax.servlet.annotation.WebServlet;
+import javax.servlet.http.HttpServletRequest;
+
+import org.eclipse.jetty.servlets.EventSource;
+import org.eclipse.jetty.servlets.EventSourceServlet;
+
+@WebServlet(urlPatterns = "/talk", initParams = { @WebInitParam(name = "heartBeatPeriod", value = "5") }, asyncSupported = true)
+public class MySSEServlet extends EventSourceServlet {
+	private static final long serialVersionUID = 1L;
+
+	@Override
+	protected EventSource newEventSource(final HttpServletRequest req) {
+		return new EventSource() {
+
+			@Override
+			public void onOpen(final Emitter emitter) throws IOException {
+				emitter.data("new server event " + new Date().toString());
+				while (true) {
+					System.out.println("propagating event..");
+					try {
+						Thread.sleep(5000);
+						emitter.data("new server event "
+								+ new Date().toString());
+					} catch (InterruptedException e) {
+						e.printStackTrace();
+					}
+				}
+			}
+
+			@Override
+			public void onClose() {
+				System.out.println("closed");
+			}
+		};
+	}
+}

src/main/webapp/WEB-INF/web.xml

+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!DOCTYPE web-app
+    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
+    "http://java.sun.com/dtd/web-app_2_3.dtd">
+<web-app>
+	<welcome-file-list>
+		<welcome-file>index.html</welcome-file>
+	</welcome-file-list>
+</web-app>    

src/main/webapp/index.html

+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8" />
+</head>
+<body>
+	<input type="button" id="stopButton" value="Stop Listening"/>
+	<hr/>
+	<div id="content"></div>
+	<script>
+    var source = new EventSource('/talk');
+    source.addEventListener('open', function(e) {
+    	  document.getElementById('content').innerHTML += 'Connections to the server established..<br/>';
+    }, false);
+    source.onmessage = function(e) {
+      document.getElementById('content').innerHTML += e.data + '<br/>';
+    };
+    document.getElementById('stopButton').onclick=function(){
+    	document.getElementById('content').innerHTML += 'Listening to server events stopped..<br/>';
+    	source.close();
+    }
+  </script>
+</body>
+</html>