some tweaks to the demo UDP server

This commit is contained in:
Trolli Schmittlauch 2020-04-05 19:58:33 +02:00
parent 303a6ecbfa
commit 6958fc2f98

View file

@ -1,7 +1,8 @@
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Network.Socket hiding (sendTo, recvFrom)
import Network.Socket hiding (send, sendTo, recv, recvFrom)
import Network.Socket.ByteString
import Control.Concurrent
import Control.Exception
@ -15,19 +16,20 @@ import qualified Data.ByteString as BS
main = do
sock <- socket AF_INET6 Datagram defaultProtocol
let hints = defaultHints { addrFamily = AF_INET6, addrSocketType = Datagram}
addrInfos <- getAddrInfo (Just hints) (Just "::1") (Just "7331")
let serverAddr = addrAddress . head $ addrInfos
serverAddr <- addrAddress . head <$> getAddrInfo (Just hints) (Just "::1") (Just "7331")
print serverAddr
bind sock serverAddr
print sock
forever $ do
receivedStuff <- recvFrom sock 65535 -- blocks
forkIO $ bracket newSendSocket close' (serveReceive receivedStuff)
return ()
forkIO $ bracket newSendSocket close (serveReceive receivedStuff)
serveReceive :: (BS.ByteString, SockAddr) -> Socket -> IO ()
serveReceive (msg, fromAddr) sendSocket = do
print sendSocket
putStrLn $ "Got message " ++ show msg ++ " from " ++ show fromAddr
sendTo sendSocket ("Hi, thx for " `BS.append` msg) fromAddr
sentBytes <- sendTo sendSocket ("Hi, thx for " `BS.append` msg) fromAddr
putStrLn $ "sent response of " ++ show sentBytes ++ "bytes"
return ()
newSendSocket :: IO Socket