Christopher’s posterous

Mostly programming things 
Filed under

translation

 

Clojure Translations (part one?)

This is a simple translation of some Java code into Clojure
(http://clojure.org/). I've tried to make the code idiomatic Clojure
(as far as I know it). I'm looking at the NIO libraries and the
SocketChannel in particular for doing some more intelligent two-way
network code.
 

 
; translation of the java code at:                                              
; http://java.sun.com/j2se/1.4.2/docs/guide/nio/example/TimeServer.java         
; (original copyright can be found there)                                       

(ns com.sencjw.time-server
  (:import (java.net Socket ServerSocket InetSocketAddress InetAddress)
           (java.nio ByteBuffer CharBuffer)
           (java.nio.channels ServerSocketChannel)
           (java.nio.charset Charset CharsetEncoder)
           (java.util Date)))

(set! *warn-on-reflection* true)

(defn serv
  "Starts a time server on a high (8013 default) port"
  ([] (serv 8013))
  ([port]
     (let [charset (.. Charset (forName "US-ASCII"))
           encoder (.newEncoder charset)
           buff (.. ByteBuffer (allocateDirect 1024))
           ssc (ServerSocketChannel/open)               ; create ServSockChan   
           addr (InetSocketAddress. port)
           _ (.bind (.socket ssc) addr)
           sc (.accept ssc)                             ; accept the connection
           now (str (Date.))]
       (try
        (.write sc (.encode encoder (CharBuffer/wrap (str now "\r\n"))))
        (println (str (.. sc (socket) (getInetAddress)) ": " now))
        (.close sc)
        (finally (.close sc))))))

(serv)

Filed under  //   clojure   code   java   lisp   translation  

Comments [1]