Restlet streaming with Thread.sleep()

天大地大妈咪最大 提交于 2019-12-11 07:38:28

问题


This example is based on an example from the book Restlet in Action.

If I try

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;
    }
}

it works and it continuously sends the json string to the client.

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)
    {} 
}

I was hoping that the client would get data 4 times in a second BUT nothing seems to get to the client.

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?


回答1:


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.

You can also try the Simple extension which has less dependent JARs than the Jetty extension.




回答2:


You can try to flush the buffer, like this:

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

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

Without writer.flush(), the writer waits to fill the internal buffer before writing the socket. Thread.sleep(250) reduces the output produced at each second, so that far more time is required to fill the buffer.



来源:https://stackoverflow.com/questions/16105665/restlet-streaming-with-thread-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!