teensyp.server

The main server namespace.

close

(close socket)(close socket callback)

Queue the supplied Socket to be closed. Accepts an optional, zero argument callback that will be run after the socket has been closed.

pause-reads

(pause-reads socket)(pause-reads socket callback)

Pause reads for this Socket. See: resume-reads.

resume-reads

(resume-reads socket)(resume-reads socket callback)

Resume reads for this Socket. See: pause-reads.

Socket

protocol

A protocol representing a client socket. See also: write, close, pause-reads and resume-reads.

members

queue-write

(queue-write socket buffer callback)

Queue the buffer to be written to the socket. If the callback is not nil, it will be called as a zero argument function once the buffer has been written. See write for a more convenient way of calling this method.

socket-info

(socket-info socket)

Return a map of information about the socket’s connection. This includes keys for :local-address and :remote-address, which are immutable java.net.InetSocketAddress instances.

start-server

(start-server {:keys [port executor recv-buffer-size reuse-address?], :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)
  • :recv-buffer-size - the receive buffer size (i.e. the SO_RCVBUF option)
  • :reuse-address? - sets the SO_REUSEADDR socket option (default false)
  • :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
  ([socket] initial-state)           ;; on socket accept
  ([state socket buffer] new-state)  ;; on socket read data
  ([state exception]))               ;; on socket close

The buffer is a java.nio.ByteBuffer instance, and socket is an object that satisfies the Socket protocol.

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.

write

(write socket buffer)(write socket buffer callback)

Queue up a ByteBuffer to be written a socket defined by the Socket protocol. Accepts an optional, zero argument callback function that will be run after the buffer has been written.