---
title: "《HTML5数据推送应用开发》源码java版之一-----helloworld"
author: "fm2005"
date: "2014-11-23T14:09:00Z"
tags: []
slug: "html5-java-helloworld"
draft: false
lastmod: "2014-12-05T23:32:19Z"
id: 2163727
url: "https://okuc.iteye.com/blog/2163727"
---

1.新建servelet，然后进行编码，最后编码完后的源码如下：

```
package com.heetian.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SSEEchoServlet
 */
@WebServlet("/SSEEchoServlet")
public class SSEEchoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/event-stream");//设置事件流
		response.setCharacterEncoding("UTF-8");//设置编码
                //获取最新时间并返回
		PrintWriter writer = response.getWriter();
		String string = new Date().toString();
		System.out.println(string);
		// send SSE
		writer.write("data: " + string + "\n\n");
		try {   //设置间隔时间
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
```

2.新建index.html文件，然后进行编码。编码后的文件如下：

```
        <!doctype html>
        <html>
          <head>
            <meta charset="UTF-8">
            <title>Basic SSE Example</title>
          </head>
          <body>
            <pre id="x">初始化...</pre><!--之所以用pre，没用div或p，是为了确保（包括换行的数据能够以它被接收时的格式呈现，而不会被修改或格式化。）-->
            <script>
            var es = new EventSource("SSEEchoServlet");//创建EventSource对象，将要连接的URL作为它唯一的参数。这里是连接到basic_sse.php
            es.addEventListener("message", function(e){
              document.getElementById("x").innerHTML += "\n" + e.data;//运态修改页面内容。
              },false);
            </script>。
          </body>
        </html>
```

3\. 运行后，可以看到浏览器中不停输出时间。效果如下：

```
初始化...
Sun Nov 23 13:56:22 CST 2014
Sun Nov 23 13:56:27 CST 2014
Sun Nov 23 13:56:31 CST 2014
Sun Nov 23 13:56:35 CST 2014
Sun Nov 23 13:56:39 CST 2014
Sun Nov 23 13:56:43 CST 2014
Sun Nov 23 13:56:47 CST 2014
Sun Nov 23 13:56:51 CST 2014
Sun Nov 23 13:56:55 CST 2014
Sun Nov 23 13:56:59 CST 2014
Sun Nov 23 13:57:03 CST 2014
。
```

**说明**：

1\. 本系列是根据《Data Push Apps with HTML5 SSE》一书的源码修改而成，该书源码为PHP版，本人在学习过程中，根据个人需求及理解，修改成了JAVA版。所以有关例子的细节，请参阅该书。

2.本系列工程使用maven管理。如果对maven不了解，请自行google或baidu。或者自行将maven工程转化为普通java工程，项目所依赖jar包，请参见pom.xml。

3.本系列博客为原创，谢绝转载。