default.txt 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. {-# LANGUAGE TypeSynonymInstances #-}
  2. module Network.UDP
  3. ( DataPacket(..)
  4. , openBoundUDPPort
  5. , openListeningUDPPort
  6. , pingUDPPort
  7. , sendUDPPacketTo
  8. , recvUDPPacket
  9. , recvUDPPacketFrom
  10. ) where
  11. import qualified Data.ByteString as Strict (ByteString, concat, singleton)
  12. import qualified Data.ByteString.Lazy as Lazy (ByteString, toChunks, fromChunks)
  13. import Data.ByteString.Char8 (pack, unpack)
  14. import Network.Socket hiding (sendTo, recv, recvFrom)
  15. import Network.Socket.ByteString (sendTo, recv, recvFrom)
  16. -- Type class for converting StringLike types to and from strict ByteStrings
  17. class DataPacket a where
  18. toStrictBS :: a -> Strict.ByteString
  19. fromStrictBS :: Strict.ByteString -> a
  20. instance DataPacket Strict.ByteString where
  21. toStrictBS = id
  22. {-# INLINE toStrictBS #-}
  23. fromStrictBS = id
  24. {-# INLINE fromStrictBS #-}
  25. openBoundUDPPort :: String -> Int -> IO Socket
  26. openBoundUDPPort uri port = do
  27. s <- getUDPSocket
  28. bindAddr <- inet_addr uri
  29. let a = SockAddrInet (toEnum port) bindAddr
  30. bindSocket s a
  31. return s
  32. pingUDPPort :: Socket -> SockAddr -> IO ()
  33. pingUDPPort s a = sendTo s (Strict.singleton 0) a >> return ()