确定远程设备端点UDP Clojure CLR

时间:2015-04-10 03:10:57

标签: .net clojure udp ref clojureclr

尝试在Clojure CLR中执行等效的c#代码

using System.Net;
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remote = (EndPoint) sender;
recv = sock.ReceiveFrom(data, ref remote);

我在Clojure中尝试过的不起作用:

(let [
      sender (IPEndPoint. (IPAddress/Any) 0)
      ^EndPoint remote ^EndPoint sender
      recv (.ReceiveFrom sock data (by-ref remote))
      ]
      (println (.ToString remote))
      ;; Do something with data...
 )

它只显示0.0.0.0:0我认为引用不起作用但也不确定提示/强制语法。

我已经在这里查看有关参考https://github.com/richhickey/clojure-clr/wiki/CLR-Interop的信息 这里是关于指定类型:https://github.com/clojure/clojure-clr/wiki/Specifying-types

1 个答案:

答案 0 :(得分:0)

我翻译了该问题评论中引用的MSDN文章。

(ns test.me
    (:import [System.Net IPHostEntry Dns IPEndPoint EndPoint IPAddress]
             [System.Net.Sockets Socket SocketType ProtocolType]))

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

(defn f []
   (let [hostEntry (Dns/GetHostEntry (Dns/GetHostName))
         endPoint (IPEndPoint. ^IPAddress (first (.AddressList hostEntry)) 11000)
         sender (IPEndPoint. (IPAddress/IPv6Any) 0)
         msg (byte-array 256)]       
     (with-open [s (Socket. (.AddressFamily (.Address endPoint))
                            SocketType/Dgram
                            ProtocolType/Udp)]
       (.Bind s endPoint)
       (.ReceiveFrom s  msg (by-ref sender))
       (println sender))))

运行它会产生:

>Clojure.Main.exe
Clojure 1.7.0-master-SNAPSHOT
user=> (load "/test/me")
nil
user=> (in-ns 'test.me)
#object[Namespace 0xaca85c "test.me"]
test.me=> (f)
#object[IPEndPoint 0x2126697 [fefe::3030:cfdf:f7f7:ecec%11]:55056]
nil

(已编辑的IP地址)

您可能需要为系统调整IPAddress/IPv6Any

with-open表单用于在退出时自动关闭套接字。

请注意,只需要很少的类型提示(实际上是一个)。我已经开启了反射警告 - 这是确定是否需要更多提示的最佳方法。 (在这种情况下,没有^IPAddress类型提示,加载失败并显示错误,因为它无法解析IPEndPoint构造函数。)