       (doto s1
         (.configureBlocking false)))))
 
+(defn new-selector [channel ops]
+  (let [s (Selector/open)]
+    (.register channel s (poll-ops-mask ops))
+    s))
+
+(defn update-selector-for-writing [selector w]
+  (when-not (:eof? w)
+    (let [c (:to-channel w)]
+      (run! #(or (= c (.channel %)) (.cancel %)) (.keys selector))
+      (.register c selector (poll-ops-mask [:write]))
+    selector)))
+
+
 (defn backend [serversocket host port finished-ch]
-  (let [bytebuffer (ByteBuffer/allocate 8192)]
+  (let [bytebuffer (ByteBuffer/allocate 8192)
+        selector (new-selector serversocket [:accept])
+        write-selector (Selector/open)]
     (loop [pending-write false
            downstreams-for-upstreams {}]
       ;; BACKPRESSURE - we do things in a very specific order.  This is

              :c2
              :write)))))


(defn poll-channels [poll-set timeout]
  (with-open [bo (reduce (fn [s [channel & ops]]

            (and pending-write (:eof? pending-write))
            (let [fch (:from-channel pending-write)
                  tch (:to-channel pending-write)]
              (.close fch)              ;this also causes removal of these
              (.close tch)              ;channels from the selector
              (recur nil (dissoc downstreams-for-upstreams fch tch)))

            ;; First deal with any unwritten buffer to/from the
            ;; downstream.  We do not
            ;; get past this point until the in-flight buffer is disposed of

            pending-write
