Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

html - Java servlet and server sent events

Is it possible to create a server sent event using java servlets so that a client could receive updates using:

 <script>
   var source = new EventSource('/events');
   source.onmessage = function(e) {
     document.body.innerHTML += e.data + '<br>';
   };
 </script>

All examples I have found on the web are using PHP but I would assume that it should work using Java's HTTP Servlet.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

this does the trick.

HTML

<!DOCTYPE html>


<html>
<body onload ="registerSSE()" >
    <script>

        function registerSSE()
        {
            alert('test 1');
            var source = new EventSource('http://frewper:8080/hello/sse');  
            alert('Test2');
            source.onmessage=function(event)
            {
                document.getElementById("result").innerHTML+=event.data + "<br />";
            };

            /*source.addEventListener('server-time',function (e){
                alert('ea');
            },true);*/
        }
    </script>
    <output id ="result"></output>

</body>
</html>

Servlet :

import java.io.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




public class sse extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
    try
    {
        System.out.println("SSE Demo");
        response.setContentType("text/event-stream");

        PrintWriter pw = response.getWriter();
        int i=0;
        while(true)
        {

            i++;
            pw.write("event: server-time

");  //take note of the 2 
 's, also on the next line.
            pw.write("data: "+ i + "

");
            System.out.println("Data Sent!!!"+i);
            if(i>10)
            break;
        }
        pw.close();

    }catch(Exception e){
        e.printStackTrace();
    }
}

public void doGet(HttpServletRequest request,HttpServletResponse response)  
{
    doPost(request,response);
}

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...