gpt4 book ai didi

java - ReSTLet 使用 Thread.sleep() 进行流式传输

转载 作者:行者123 更新时间:2023-11-29 05:45:08 25 4
gpt4 key购买 nike

此示例基于 ReSTLet in Action 一书中的示例。

如果我尝试

public class StreamResource extends ServerResource
{
@Get
public Representation getStream() throws ResourceException, IOException
{
Representation representation = new WriterRepresentation(MediaType.TEXT_PLAIN)
{
@Override
public void write(Writer writer) throws IOException
{
String json = "{\"foo\" : \"bar\"}";
while (true)
{
writer.write(json);
}
}
};

return representation;
}
}

它可以正常工作,并不断向客户端发送 json 字符串。

如果我像这样在 while 循环中引入延迟

String json = "{\"foo\" : \"bar\"}\r\n";

while (true)
{
writer.write(json);
try
{
Thread.sleep(250);
}
catch (InterruptedException e)
{}
}

我希望客户端在一秒钟内获得 4 次数据,但似乎什么也没有到达客户端。

谁能解释为什么引入 Thread.sleep() 会这样?向客户端引入流数据延迟的好方法是什么?

最佳答案

您应该尝试使用 Jetty 连接器而不是内部 ReSTLet 连接器。尽管我们正在努力修复此连接器,但它尚未准备好投入生产。

您也可以尝试 Simple 扩展,它比 Jetty 扩展具有更少的依赖 JAR。

关于java - ReSTLet 使用 Thread.sleep() 进行流式传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16105665/

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