问题描述
此示例基于 Restlet in Action
一书中的示例.
This example is based on an example from the book 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 字符串发送到客户端.
it works and it continuously sends the json string to the client.
如果我像这样在 while 循环中引入延迟
If I introduce a delay in the while loop like this
String json = "{\"foo\" : \"bar\"}\r\n";
while (true)
{
writer.write(json);
try
{
Thread.sleep(250);
}
catch (InterruptedException e)
{}
}
我希望客户端能在一秒钟内获得 4 次数据,但似乎什么也没有到达客户端.
I was hoping that the client would get data 4 times in a second BUT nothing seems to get to the client.
谁能解释为什么引入 Thread.sleep()
会这样?向客户端引入流数据延迟的好方法是什么?
Can anyone explain why the introduction of Thread.sleep()
does that? What is a good way to introduce delay in streaming data to the client?
推荐答案
您应该尝试使用 Jetty 连接器而不是内部 Restlet 连接器.尽管我们正在修复它,但该连接器尚未准备好投入生产.
You should try with the Jetty connector instead of the internal Restlet connector. This connector isn't ready for production even though we are working on fixing it.
您还可以尝试使用比 Jetty 扩展更少依赖 JAR 的 Simple 扩展.
You can also try the Simple extension which has less dependent JARs than the Jetty extension.
这篇关于Restlet 流与 Thread.sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!