summaryrefslogtreecommitdiff
path: root/Network/Run/UDP.hs
blob: b64aaeddcbbf08759bf594c98ca686c3b0b9f0c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
-- | Simple functions to run UDP clients and servers.
module Network.Run.UDP (
    runUDPClient
  , runUDPServer
  ) where

import qualified Control.Exception as E
import Network.Socket

import Network.Run.Core

-- | Running a UDP client with a socket.
--   The client action takes a socket and
--   server's socket address.
--   They should be used with 'sendTo'.
runUDPClient :: HostName -> ServiceName -> (Socket -> SockAddr -> IO a) -> IO a
runUDPClient host port client = withSocketsDo $ do
    addr <- resolve Datagram (Just host) port False
    let sockAddr = addrAddress addr
    E.bracket (openSocket addr) close $ \sock -> client sock sockAddr

-- | Running a UDP server with an open socket.
runUDPServer :: Maybe HostName -> ServiceName -> (Socket -> IO a) -> IO a
runUDPServer mhost port server = withSocketsDo $ do
    addr <- resolve Datagram mhost port True
    E.bracket (openServerSocket addr) close server