[Haskell-cafe] `Expect'-like lazy reading/Parsec matching on TCP sockets

Scott Bell sebell at gmail.com
Thu Apr 5 10:18:58 EDT 2007


Bulat,

> yes, with both variants. actually, second one should be easier to
> implement and understand. you should look into unsafeInterleaveIO
> section of http://haskell.org/haskellwiki/IO_inside

This seems to do what I want, and unless I'm overlooking something
it feels very straight-forward:

hGetContentsTimeout :: Handle -> Int -> IO String
hGetContentsTimeout h t = do
  hSetBuffering stdin NoBuffering
  ready <- hWaitForInput h t
  if (not ready) then return []
    else do
      c <- hGetChar h
      s <- unsafeInterleaveIO (hGetContentsTimeout h t)
      return (c:s)

This is not extensivly tested, but applying my parser to the string
returned by hGetContentsTimeout behaves precisely as I wanted:

It returns a match as soon as it is available, and fails if it is not
seen within t ms.

Thanks for your help!

- Scott


More information about the Haskell-Cafe mailing list