为了学习conduit
库的基础知识,我曾经network-conduit
制作了一个简单的回显服务器:
import Control.Monad.IO.Class
import qualified Data.ByteString.Char8 as BS
import Data.Conduit
import Data.Conduit.Network
-- A conduit that print the input it receives on the console
-- and passes it through.
echo :: (MonadIO m) => Conduit BS.ByteString m BS.ByteString
echo = do
yield (BS.pack "Anything you type will be echoed back.\n")
-- Print the received data to the console as well:
awaitForever (\x -> liftIO (BS.putStr x) >> yield x)
echoApp :: (MonadIO m) => Application m
echoApp appData = appSource appData $= echo $$ appSink appData
-- Listen on port 4545:
main :: IO ()
main = runTCPServer (serverSettings 4545 HostAny) echoApp
它做了我想要的,但是当客户端关闭它的连接部分时,服务器仍在等待输入,而不是写出任何剩余的数据并关闭它的连接发送部分:
$ nc localhost 4545 <<<"Hello world!"
Anything you type will be echoed back.
Hello world!
我试着删除echo
并做
echoApp appData = appSource appData $$ appSink appData
但问题仍然存在。我究竟做错了什么?