gpt4 book ai didi

servlets - 文本/事件流从头开始渲染(没有插件)

转载 作者:行者123 更新时间:2023-12-02 14:58:30 24 4
gpt4 key购买 nike

要使用push方法,我们使用著名的JS对象EventSource:

这是易于开发的客户端部分:

        var eventSource = new EventSource("controller/action");

eventSource.onmessage = function(event) {

document.getElementById('foo').innerHTML = event.data;

};

但是,我很难在服务器部分(Grails)中配置push方法。

当我查看由Servlets开发的JEE应用程序时,我可以看到服务器部分如下:

http://viralpatel.net/blogs/html5-server-sent-events-java-servlets-example/
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();
}
}

要将这个servlet转换为 Action Controller :
def push(){

render(contentType:'text/event-stream',characterEncoding:'UTF-8'){
[dt:"data: "+ System.currentTimeMillis() +"\n\n"]
}
}

在客户端部分:
 var eventSource = new EventSource(baseURL+"external/push");
eventSource.onmessage=function(e){
console.log(e.data.dt);
}

不幸的是,我在console上没有任何结果。

最佳答案

我不确定render方法是否可以正确处理'text/event-stream',但是您可以直接在操作中访问response对象:

def push() {
//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");

for(int i=0; i<10; i++) {

response.outputStream.write("data: "+ System.currentTimeMillis() +"\n\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
response.outputStream.flush()
}

关于servlets - 文本/事件流从头开始渲染(没有插件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21402670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com