Monday, December 7, 2015

Play Framework websocket connection keep-alive with play.libs.F.Timeout

Hello,

Play Framework has web socket capability. However, if you are using web socket protocol with F5 load-balancer, it's possible that inactive connection will be dropped by F5 and your socket connection will be lost forever.

I suggested sending null message to the client side frequently if there is no new data to keep-alive the connection. However, what if you job takes too much time to complete? You cannot send anything, not even null to the client side. Here is what I found as a solution to this problem:

public static void getLatestAval()
{
        while(inbound.isOpen())
        {
            //send null every 100 seconds if the job does not finish
            Promise task = StatefulModel.instanceAval.eventAval.nextEvent();
            Either<List<Object>, Timeout> r = await(Promise.waitEither(task, play.libs.F.Timeout(1000000)));

            for(Timeout t : r._2)
            {              
                if(task.isDone())
                {
                    if(outbound.isOpen())
                        outbound.sendJson(r._1);                  
                }
                else if(t.isDone()) //timeout
                {
                     if(outbound.isOpen())                    
                        outbound.sendJson(null);                   
                }
            }
       }
 }

Cheers,