我需要在客户端之间来回做一些,并在启动更多管道之前获取Client对象或其名称字符串。
但我似乎无法让appSink让我有一个返回值。
我该怎么做?
checkAddClient :: Server -> ClientName -> AppData -> IO (Maybe Client)
checkAddClient server@Server{..} name app = atomically $ do
clientmap <- readTVar clients
if Map.member name clientmap
then return Nothing
else do
client <- newClient name app
writeTVar clients $ Map.insert name client clientmap
return (Just client)
readName server app = go
where
go = do
yield "What is your name? "
name <- lineAsciiC $ takeCE 80 =$= filterCE (/= _cr) =$= foldC
if BS.null name
then go
else do
ok <- liftIO $ checkAddClient server name app
case ok of
Nothing -> do
yield . BS.pack $ printf "The name '%s' is in use, please choose another\n" $ BS.unpack name
go
Just client -> do
yield . BS.pack $ printf "Welcome, %s!\n" $ BS.unpack name
return client -- <-- Here is the problem!!
main :: IO ()
main = do
server <- newServer
runTCPServer (serverSettings 4000 "*") $ \clientApp -> do
(clientC, client) <- appSource clientApp $$+ readName server clientApp =$ appSink clientApp
更新
以下是我最终解决的问题:
readName :: Server -> AppData -> Sink BS.ByteString IO Client
readName server app = go
where
go = do
yield "What is your name? " $$ appSink app
name <- lineAsciiC $ takeCE 80 =$= filterCE (/= _cr) =$= foldC
if BS.null name
then go
else do
ok <- liftIO $ checkAddClient server name app
case ok of
Nothing -> do
yield (BS.pack $ printf "The name '%s' is in use, please choose another\n" $ BS.unpack name) $$ appSink app
go
Just client -> do
yield (BS.pack $ printf "Welcome, %s!\n" $ BS.unpack name) $$ appSink app
return client
main :: IO ()
main = do
server <- newServer
runTCPServer (serverSettings 4000 "*") $ \clientC -> do
client <- appSource clientC $$ readName server clientC
print $ clientName client
答案 0 :(得分:1)
这是主要管道API的限制:您无法从最下游组件获取结果值。有一些解决方法:
有一个更高级的管道API, 允许捕获上游终结器。您感兴趣的功能是withUpstream。请注意,这是&#34;权利&#34;解决问题的方法,但是这个更高级的API并不是主要的原因:它有六个类型参数,往往会让人感到困惑。
不是将readName
与appSink
融合,而是将appSink
传递给readName
,并在每次yield
来电时将其融合。 E.g:
yield (BS.pack $ printf "...") $$ appSink app
这可能是简单性和类型安全性之间的最佳平衡。
创建IORef
或其他可变变量,并将客户端的名称放入该可变变量中。