teensyp.server

The main server namespace.

CLOSE

A unique identifier that can be passed to the write function of a handler in order to close the connection.

PAUSE-READS

A unique identifier that can be passed to the write function of a handler in order to pause reads. See: RESUME-READS.

RESUME-READS

A unique identifier that can be passed to the write function of a handler in order to pause reads. See: PAUSE-READS.

start-server

(start-server {:keys [port executor], :as opts})

Start a TCP server with the supplied map of options:

  • :port - the port number to listen on (mandatory)
  • :handler - a handler function (mandatory, see below)
  • :executor - a custom ExecutorService to supply worker threads
  • :read-buffer-size - the read buffer size in bytes (default 8K)
  • :write-buffer-size - the write buffer size in bytes (default 32K)
  • :write-queue-size - the max number of writes in the queue (default 64)

The handler function must have three arities:

(fn handler
  ([write] initial-state)           ;; on socket accept
  ([state buffer write] new-state)  ;; on socket read data
  ([state exception]))              ;; on socket close

The buffer is a java.nio.ByteBuffer instance, and write is a function that takes a buffer as an argument and will queue it to send to the client. To close the channel, pass CLOSE to the write function.

The write function may also take PAUSE-READS and RESUME-READS. These will pause and resume reads calls respectively.

You may optionally specify a second argument to write. This is should be a zero-argument callback function, which is called after the write completes.

The state is a custom data structure that is returned when the accept or read arities are triggered. A different state is associated with each connection.

When closing, the exception may contain the exception that terminated the channel, or nil if the channel were terminated gracefully.

The handler function is guaranteed to execute in serial per channel. That is, the accept will always be first, the close will always be last, and reads will always be sequential.