Swift Network.framework Study 20191210「Bonjour Browse」

Study

Network.framework
Study:「Bonjour Browse」

環境

Client:Java、NetBeans、jmdnsライブラリ
https://github.com/jmdns/jmdns
Server:Swift、Xcode

Client Source Java

package example.java.network;

import java.net.InetAddress;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;

public class ExampleBonjourCreateService {
    public static void main(String[] args) {
        try {
            // Create a JmDNS instance
            JmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());

            // Register a service
            ServiceInfo serviceInfo = ServiceInfo.create("_example._tcp.local.", "example", 7777, "example");
            jmdns.registerService(serviceInfo);

            // Wait a bit
            Thread.sleep(25000);

            // Unregister all services
            jmdns.unregisterAllServices();

        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}

build.gradle

compile 'org.openhab.jmdns:jmdns:3.4.2'

Server Source Swift

main.swift

import Foundation
import Network

if #available(OSX 10.15, *) {
    let exampleNWBrowser = ExampleNWBrowser()
    exampleNWBrowser.startBrowser()

    while exampleNWBrowser.running {
        sleep(1)
    }
} else {
    // Fallback on earlier versions
}

ExampleNWBrowser.swift

import Foundation
import Network

@available(OSX 10.15, *)
class ExampleNWBrowser {
    public var running = true
    private var browser:NWBrowser?

    func startBrowser() {
        let myQueue = DispatchQueue(label: "ExampleNetwork")
        let nWBrowser = NWBrowser(for: .bonjour(type: "_example._tcp", domain: nil), using: NWParameters())
        self.browser = nWBrowser
        browser!.stateUpdateHandler = {(state) in
            print("State:\(state)")
        }
        browser!.browseResultsChangedHandler = { (results, changes) in
            print("browseResultsChangedHandler")
            for result in results {
                print(result)
            }
            for change in changes {
                print(change)
            }
        }
        browser!.start(queue: myQueue)
        print("start")
    }
}

Output

start
State:ready
browseResultsChangedHandler
Result(nw: example._example._tcp.local.@[en0], endpoint: example._example._tcplocal., interfaces: [en0], metadata: <none>)
added(Network.NWBrowser.Result(nw: example._example._tcp.local.@[en0], endpoint: example._example._tcplocal., interfaces: [en0], metadata: <none>))
browseResultsChangedHandler
removed(Network.NWBrowser.Result(nw: example._example._tcp.local.@[en0], endpoint: example._example._tcplocal., interfaces: [en0], metadata: <none>))

ResultにEndPointが入っている
EndPointを使用すれば、送信・受信は可能となる

Swift

Posted by shi-n