[web-devel] Handling disconnection in wai or warp

Gregory Collins greg at gregorycollins.net
Mon Aug 29 15:10:13 CEST 2011


Correct, with either WAI or Snap you will need to write an enumerator
to do this.

I don't know much about WAI, but with Snap you may also need to call
"getTimeoutAction :: MonadSnap m => m (Int -> IO ())" in order to get
a closure that you can use within your enumerator to prevent the
long-running connection from timing out (the default is something like
20s IIRC).

In Snap (and likely also in WAI), if the client connection is
disconnected, unless you have some side-effecting cleanup to do, you
shouldn't need to do anything special. If you do need to run some
side-effecting cleanup code, you should be able to catch the exception
thrown by the socket iteratee using the MonadCatchIO instance provided
in Snap.

G

On Mon, Aug 29, 2011 at 12:07 PM, Michael Snoyman <michael at snoyman.com> wrote:
> On Mon, Aug 29, 2011 at 1:03 PM, Hiromi ISHII <konn.jinro at gmail.com> wrote:
>> Hi there,
>>
>> I am writing a simple server which returns infinite stream of data to client like Twitter's streaming API.
>>
>> I have to manage the number of clients and the connection times of each one.
>> So I have to handle disconnections during server sending a response to the client.
>>
>> I'm currently considering using wai (+warp) or snap framework.
>> My code fragments for snap and wai are below:
>>
>> ==== snap ver. application ====
>> stream :: Application ()
>> stream = do
>>  req <- withRequest $ return . (rqRemoteAddr &&& rqRemotePort)
>>  writeLBS $ LBS.unlines $ map (LBS.pack . show) [1..] -- I have to handle disconnection here
>> ==== end ====
>>
>> ==== wai ver. ====
>> streamHandler :: Application
>> streamHandler req = do
>>  return $ responseLBS statusOK
>>                       [ ("Content-Type", "application/json")
>>                       , ("Transfer-Encoding", "chunked")
>>                       ]
>>                       (LBS.unlines $ map (LBS.pack . show) [1..]) -- I have to handle disconnection here
>> ==== end ====
>>
>>
>> Thanks,
>>
>> -- Hiromi ISHII
>> _______________________________________________
>> web-devel mailing list
>> web-devel at haskell.org
>> http://www.haskell.org/mailman/listinfo/web-devel
>>
>
> I'm not entirely certain what's going on here, but my guess is that
> for either WAI or Snap you'd want to use the enumerator interface
> instead of lazy ByteStrings. Also, for WAI, you should *not* set the
> transfer-encoding, that is something the backend handles for you
> automatically.
>
> Michael
>
> _______________________________________________
> web-devel mailing list
> web-devel at haskell.org
> http://www.haskell.org/mailman/listinfo/web-devel
>



-- 
Gregory Collins <greg at gregorycollins.net>



More information about the web-devel mailing list