import Control.Concurrent
import Data.ByteString (hGetSome)
import Network
import System.IO

main :: IO ()
main = do
    let port = PortNumber 1234
    hSetBuffering stdout LineBuffering
    serverListening <- newEmptyMVar
    serverSent      <- newEmptyMVar

    _ <- forkIO $ do
        sock <- listenOn port
        putMVar serverListening ()

        (h, _, _) <- accept sock
        hSetBuffering h LineBuffering
        hPutStrLn h "One"
        hPutStrLn h "Two"

        putMVar serverSent ()

        -- Prevent handle from being garbage collected
        threadDelay 100000000
        hPutStrLn h "Bye"

    takeMVar serverListening

    putStrLn "Connecting and getting first line"
    h <- connectTo "localhost" port
    hGetLine h >>= putStrLn

    takeMVar serverSent

    putStrLn "hWaitForInput"
    ready <- hWaitForInput h 1000
    putStrLn $ "ready: " ++ show ready

    putStrLn "hGetSome"
    s <- hGetSome h 4096
    putStrLn $ "Got " ++ show s
