5

对于我正在编写的 IRC 机器人,我想继续尝试打开一个套接字,即使有一个UnkownHostException. 我的第一个想法是这样的。

(defn open-socket [{:keys [host port] :as connection}]
  (try (java.net.Socket. host port)
    (catch java.net.UnknownHostException _ (recur connection))))

但它不起作用,因为您不能从 catch 块中重现。所以相反,我选择了这样的东西:

  (let [socket (promise)
        _ (while (not (realized? socket))
            (try (deliver socket (java.net.Socket. host port))
              (catch java.net.UnknownHostException _)))
        socket @socket]
    ...

这很有效,但非常必要。有没有一种我看不到的更实用的方法可以做到这一点?

4

2 回答 2

13

只需添加一个or

(defn open-socket [{:keys [host port] :as connection}]
  (or (try (java.net.Socket. host port)
           (catch java.net.UnknownHostException _ nil))
      (recur connection)))
于 2013-06-23T07:14:51.013 回答
0

一种可能性可能是这样的?

(let [make-socket #(try (java.net.Socket. host port)
                     (catch java.new.UnknownHostException _))
      socket-attempts (repeatedly make-socket)
      socket (first (drop-while nil? socket-attempts))]
  socket)
于 2013-06-23T05:51:34.063 回答