我有一个UDP服务器,它会反射接收到的每个ping消息(我认为这很有效)。在客户端,我想要做两件事:
此外,我非常惊讶看到函数
- 确保我发送了N个(例如10000)消息,以及
- 计算正确接收到的响应数量。
forkIO
的原因,我的客户端代码在结束时过早或根本没有进行任何计数。此外,我非常惊讶看到函数
tryOnePing
返回250次Int 4。这可能是什么原因?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
和相关函数可以在Control.Monad
中找到。 - hammar