【发布时间】:2011-11-26 03:10:04
【问题描述】:
我有一个 UDP 服务器,它反映了它收到的每条 ping 消息(我认为这很好用)。我是客户端,然后我想做两件事:
- 确保我发送了 N(例如 10000)条消息,并且
- 计算正确收到的响应数。
似乎由于 UDP 的性质或由于 forkIO 的事情,我下面的客户端代码过早结束/根本不做任何计数。
我也很惊讶地看到函数tryOnePing 返回了 Int 4 的 250 倍。为什么会这样?
main = withSocketsDo $ do
s <- socket AF_INET Datagram defaultProtocol
hostAddr <- inet_addr host
thread <- forkIO $ receiveMessages s
-- is there any better way to eg to run that in parallel and make sure
-- that sending/receiving are asynchronous?
-- forM_ [0 .. 10000] $ \i -> do
-- sendTo s "ping" (SockAddrInet port hostAddr)
-- actually this would be preferred since I can discard the Int 4 that
-- it returns but forM or forM_ are out of scope here?
let tryOnePing i = sendTo s "ping" (SockAddrInet port hostAddr)
pings <- mapM tryOnePing [0 .. 1000]
let c = length $ filter (\x -> x==4) pings
-- killThread thread
-- took that out to make sure the function receiveMessages does not
-- end prematurely. still seems that it does
sClose s
print c
-- return()
receiveMessages :: Socket -> IO ()
receiveMessages socket = forever $ do
-- also tried here forM etc. instead of forever but no joy
let recOnePing i = recv socket 1024
msg <- mapM recOnePing [0 .. 1000]
let r = length $ filter (\x -> x=="PING") msg
print r
print "END"
【问题讨论】:
-
forM和朋友是found inControl.Monad。
标签: networking haskell concurrency