Network programming

The POSIX environment provides basic support for network programming over TCP sockets. We repeat part of module POSIX:

module POSIX where


data Host = Host String
data Port = Port Int

struct Internet where
    tcp :: Sockets

struct Socket < Closable where
    remoteHost :: Host
    remotePort :: Port
    inFile     :: RFile
    outFile    :: WFile

struct Connection < Closable where 
    established :: Action
    neterror    :: String -> Action

struct Sockets where
   connect :: Host -> Port ->
              (Socket -> Class Connection) -> Request()
   listen  :: Port ->
              (Socket -> Class Connection) -> Request Closable

instance showHost :: Show Host
showHost = struct
   show (Host nm) = nm

Typically, a network program consists of two program parts, a client and a server, executing on different hosts, connected to the internet. The parts communicate over a socket, an abstraction of a communication channel. A socket has selectors to give the host and port of the remote peer and two files, an RFile for reading and a WFile for writing. The main body of both the server and the client is a function of type Socket -> Class Connection. This function has access to a socket and must define methods describing how to handle the events a network program must react to: an established message when the cnnection has been established, a neterror message in case of problems and a close message from the remote peer.

The client tries to connect to a server by specifying a host and a port; the server just specifies a port on which to listen. Whenever a client connects to a host on a port and there is a server listening on that port, a socket is created for each party with files set up for communication and an established message is sent to both parties. Typically, code in the body of established will register callbacks with the infiles.

For examples, see EchoServer and TCPClient.

Presently, only TCP sockets are supported. A future release may provide support for UDP sockets.