等待键盘按下而不会阻塞

时间:2014-08-07 14:06:34

标签: haskell

我当前的简单TCP echo服务器代码如下所示

import Network.Socket

main :: IO ()
main = setup

setup :: IO ()
setup = do
    sock <- socket AF_INET Stream 0
    bind sock (SockAddrInet 5000 iNADDR_ANY);
    listen sock 5
    loop sock

loop :: Socket -> IO()
loop sock = do
    conn                    <- accept sock
    handleConnection conn
    loop sock

handleConnection :: (Socket, SockAddr) -> IO ()
handleConnection (clntSock, clntAddr) = do
    putStrLn $ "Handling client: " ++ show clntAddr
    clntMsg <- recv clntSock 256
    _ <- send clntSock clntMsg
    close clntSock

循环永远运行。我尝试了几种方法来监听键盘按,然后退出。但他们都阻止了主循环。因此服务器没有响应客户端而只是等待按键。

如何在仍然为客户提供服务时与命令行进行交互?

1 个答案:

答案 0 :(得分:1)

您需要wait for input,可能是standard in

稍微修改现有代码:

loop sock = do
    conn <- accept sock
    handleConnection conn
    done <- hWaitForInput stdin 1
    if done then return () else loop sock

您还需要添加此导入:

import System.IO (hWaitForInput, stdin)