5.2. Socket: The high-level networking interface

The Socket interface is a ``higher-level'' interface to sockets, and it is what we recommend. Please tell us if the facilities it offers are inadequate to your task! The interface is relatively modest:

data Socket     -- instance of: Eq, Show

data PortID =
      Service String        -- Service Name eg "ftp"
    | PortNumber PortNumber -- User defined Port Number
    | UnixSocket String     -- Unix family socket in file system,
                            -- not available con Cygwin/Mingw
type Hostname    = String

connectTo       :: Hostname -> PortID -> IO Handle
listenOn        :: PortID -> IO Socket

accept          :: Socket -> IO (Handle, HostName)

sendTo          :: Hostname -> PortID -> String -> IO ()
recvFrom        :: Hostname -> PortID -> IO String

socketPort      :: Socket -> IO PortID

withSocketsDo   :: IO a -> IO a

data PortNumber -- instance of Eq, Ord, Enum, Num, Real, Integral, Show
mkPortNumber    :: Int -> PortNumber

NOTE: on Unix, when reading from a socket and the writing end is closed by the remote client, the program is normally sent a SIGHUP by the operating system. The default behaviour when a SIGHUP is received is to terminate the program silently, which can be somewhat confusing if you haven't encountered this before. The solution is to specify that SIGHUP is to be ignored, using the POSIX library (Section 7.2):

import Posix

  ...
  installHandler sigPIPE Ignore Nothing
  ...

Having done this, a read operation on a socket whose writing end has been closed will yield the expected ResourceVanished IO exception.