如何在JEE6中实现服务器发送事件 [英] how to implement server-sent-events in JEE6
问题描述
在PHP中,它非常简单:我刚刚将其添加到"b.php"中:
In PHP it really simple: I just added this to "b.php":
header('Content-Type: text/event-stream');
echo "data: Hi\n\n";
flush();
并将其保存为"a.html":
and this to "a.html":
var source = new EventSource("b.php");
source.onmessage = function (event) {
document.body.innerHTML += event.data + "<br>";
我只需要转到a.html,它就可以了!
I just need to go a.html and it's works!
但是在Java中,我尝试创建servlet,在doGet中,我添加了以下代码:
But in java I've tried to create servlet and in doGet I added this code:
response.setContentType("text/event-stream");
PrintWriter out = response.getWriter();
out.println("data: Hi\n\n") ;
out.flush();
当我转到a.html(与上面相同)时,我可以看到确实在调试器中调用了doGet,但从未发生过"onmessage"事件.
And when I go to a.html (same as above) I can see that doGet is indeed invoked (in debugger) but the "onmessage" event is never happened.
如何在JEE6中从SSE开始?有人可以给我写一个可行的例子吗?
How to start with SSE in JEE6? somebody can write me an example that works?
谢谢.
推荐答案
结帐 https://github.com/oliverwehrens/Server-Sent-Events-Java-Magazin .这是一个示例代码,可以助您一臂之力.
checkout https://github.com/oliverwehrens/Server-Sent-Events-Java-Magazin . This is an example code to get you going.
这篇关于如何在JEE6中实现服务器发送事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!