From: http://jmdns.sourceforge.net/
常摸 Apple 裝置的工程師,對 mDNS 應該不陌生,現在就來把玩一下如何在 Android 透過 mDNS 偵測裝置,所幸的已經有好人弄好 jmdns library 啦,且用起來也非常方便。
筆記一下項目:
- 在 Mac 10.8 環境下使用 dns-sd 來註冊裝置偵測資訊
- $ dns-sd -R DeviceName ServiceType ServiceDomain ServicePort TXTRecords
- 如何用 jmdns 處理 TXT record
- 可在 public void serviceResolved(ServiceEvent arg0) 裡透過 byte [] txt = arg0.getInfo().getTextBytes(); 取得資訊
- 每一組 key-value pair 前一個 byes 代表此組長度
$ killall dns-sd
No matching processes belonging to you were found
$ dns-sd -R device1 _changyytcp._tcp local 9900 k1=v1 k2=v2 k3=v3
Registering Service device1._changyytcp._tcp.local port 9900 TXT k1=v1 k2=v2 k3=v3
DATE: ---Wed 15 May 2013---
20:50:08.084 ...STARTING...
20:50:08.279 Got a reply for service device1._changyytcp._tcp.local.: Name now registered and active
No matching processes belonging to you were found
$ dns-sd -R device1 _changyytcp._tcp local 9900 k1=v1 k2=v2 k3=v3
Registering Service device1._changyytcp._tcp.local port 9900 TXT k1=v1 k2=v2 k3=v3
DATE: ---Wed 15 May 2013---
20:50:08.084 ...STARTING...
20:50:08.279 Got a reply for service device1._changyytcp._tcp.local.: Name now registered and active
代表有一個裝置名叫 device1,並宣告有 _changyytcp._tcp 型態的服務,在 local 的 domain 與 9900 port 服務,且帶有 k1=v1, k2=v2, k3=v3 三個 key-value pair 的 TXT record 資訊
處理 TXT Record 片段程式碼:
@Override
public void serviceResolved(ServiceEvent arg0) {
// TODO Auto-generated method stub
System.out.println("serviceResolve:"+arg0.getName());
public void serviceResolved(ServiceEvent arg0) {
// TODO Auto-generated method stub
System.out.println("serviceResolve:"+arg0.getName());
byte [] txt = arg0.getInfo().getTextBytes();
if (txt.length > 0) {
for( int i=0 ; i < txt.length ; ++i ) {
int len = ((int) txt[i] & 0xff); // first byte is length of the "key=value"
int begin_at = i+1;
i += len;
System.out.println("TXT KeyValuePair:["+new String( txt, begin_at, len )+"]");
}
}
}
程式輸出:
I/System.out(#): serviceResolve:device1
I/System.out(#): TXT KeyValuePair:[k1=v1]
I/System.out(#): TXT KeyValuePair:[k2=v2]
I/System.out(#): TXT KeyValuePair:[k3=v3]
I/System.out(#): TXT KeyValuePair:[k1=v1]
I/System.out(#): TXT KeyValuePair:[k2=v2]
I/System.out(#): TXT KeyValuePair:[k3=v3]
註:別忘了模擬器不支援,需用實機測試,更多程式碼可參考 https://github.com/changyy/android-mdns
Android的NSD api 不就是用mDNS嘛?
回覆刪除感謝分享。
刪除Using Network Service Discovery, http://developer.android.com/training/connect-devices-wirelessly/nsd.html
這是 Android 4.1 (API Level: 16) 才支援的。