服务器使用服务器端将事件作为servlet发送 [英] Server sent events using server side as servlets

查看:84
本文介绍了服务器使用服务器端将事件作为servlet发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用servlet运行简单服务器发送事件的实现。

I have a running implementation of simple server sent events using servlets.

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
    // TODO Auto-generated method stub

    try
    {
        System.out.println("Server Sent Events");
        response.setContentType("text/event-stream");

        PrintWriter pw = response.getWriter();
        int i=0;
        pw.write("retry: 30000\n"); 
        System.out.println("----------------------");
        while(true)
        {
            i++;

            pw.write("data: "+ i + "\n\n");
            System.out.println("Data Sent : "+i);
            if(i>10)
                break;
        }

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

我的客户端代码是

<!DOCTYPE html>
<html>
<body onload ="SSE()" >
<script>

    function SSE()
    {
        var source = new EventSource('GetDate');  
        source.onmessage=function(event)
        {
            document.getElementById("result").innerHTML+=event.data + "<br />";
        };
    }
</script>
<output id ="result"></output>

</body>
</html>

但有人能解释一下这实际上是如何运作的吗?
如同服务器如何一次性发送11个整数的块?
此处有必要刷新或关闭Printwriter。
服务器是否每次建立新连接以发送数据

But can anyone explain me how this actually works? As in how does the server send the chunk of 11 integers in one go? And is it necessary to flush or close the Printwriter here. Does the server every time makes a new connection to send the data

推荐答案

响应流将内容写入消息http包的正文。当你循环整数时,所有这些都会一个接一个地添加到内容中。除非在流上没有关闭刷新/关闭,否则您可以继续在流上写入,并且当您发送响应时,所有内容都将立即发送。

Response stream writes the content on the message body of http packet. As you are looping the integers so, all of them are getting added to the content one after the other. Unless flush/close is not closed on the stream you can keep writing on the stream and everything will by sent at once when you send the response.

还有一些关于刷新的说明你不需要使用slufh,servletcontainer会为你冲洗并关闭它。顺便说一下,关闭已经隐式调用flush.Calling flush通常只有当你在同一个流上有多个编写器并且想要切换编写器(例如带有混合二进制/字符数据的文件)时,或者当你想要保持时流指针打开一段不确定的时间(例如日志文件)。

Also some note about flush and close.You don't need to slufh,the servletcontainer will flush and close it for you. The close by the way already implicitly calls flush.Calling flush is usually only beneficial when you have multiple writers on the same stream and you want to switch of the writer (e.g. file with mixed binary/character data), or when you want to keep the stream pointer open for an uncertain time (e.g. a logfile).

这篇关于服务器使用服务器端将事件作为servlet发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆