hmm: Server Push, node.js

Beitrag lesen

hi leute,

ich hab gerade das hier ausprobiert:

http://viralpatel.net/blogs/html5-server-sent-events-java-servlets-example/

ich kann ein servlet mit einer .jsp datei aufrufen (reines java/jsp), erweitere ich das ganze aber um einen aufruf per javascript, geht der aufruf der servlets nicht mehr. muss ich node.js installieren? falls ja, wie integrier ich das in meinem eclipse projekt.

hier der code den ich zum laufen bringen möchte:

<!DOCTYPE HTML>
<html>
<body>
    Time: <span id="foo"></span>
     
    <br><br>
    <button onclick="start()">Start</button>
 
    <script type="text/javascript">
    function start() {
 
        var eventSource = new EventSource("HelloServlet");
         
        eventSource.onmessage = function(event) {
         
            document.getElementById('foo').innerHTML = event.data;
         
        };
         
    }
    </script>
</body>
</html>
package net.viralpatel.servlets;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class TestServlet extends HttpServlet {
     
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
     
        //content type must be set to text/event-stream
        response.setContentType("text/event-stream");   
 
        //encoding must be set to UTF-8
        response.setCharacterEncoding("UTF-8");
 
        PrintWriter writer = response.getWriter();
 
        for(int i=0; i<10; i++) {
 
            writer.write("data: "+ System.currentTimeMillis() +"\n\n");
 
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        writer.close();
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="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>
        <display-name>HelloServlet</display-name>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>net.viralpatel.servlets.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/HelloServlet</url-pattern>
    </servlet-mapping>
</web-app>