Search code examples
javastreamingrestlet

Restlet streaming with Thread.sleep()


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?


Solution

  • 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.