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