harmony 鸿蒙mDNS Management

2023-06-24 浏览 (1092)

mDNS Management

Overview

Multicast DNS (mDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN.

  • Local service: a service provider on a LAN, for example, a printer or scanner.

Typical mDNS management scenarios include:

  • Managing local services on a LAN, such as adding, removing, and resolving local services.
  • Discovering local services and listening to the status changes of local services of the specified type through the DiscoveryService object.

NOTE To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see mDNS Management.

The following describes the development procedure specific to each application scenario.

Available APIs

For the complete list of APIs and example code, see mDNS Management.

TypeAPIDescription
ohos.net.mdnsaddLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback<LocalServiceInfo>): voidAdds an mDNS service. This API uses an asynchronous callback to return the result.
ohos.net.mdnsremoveLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback<LocalServiceInfo>): voidRemoves an mDNS service. This API uses an asynchronous callback to return the result.
ohos.net.mdnscreateDiscoveryService(context: Context, serviceType: string): DiscoveryServiceCreates a DiscoveryService object, which is used to discover mDNS services of the specified type.
ohos.net.mdnsresolveLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback<LocalServiceInfo>): voidResolves an mDNS service. This API uses an asynchronous callback to return the result.
ohos.net.mdns.DiscoveryServicestartSearchingMDNS(): voidSearches for mDNS services on the LAN.
ohos.net.mdns.DiscoveryServicestopSearchingMDNS(): voidStops searching for mDNS services on the LAN.
ohos.net.mdns.DiscoveryServiceon(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): voidEnables listening for discoveryStart events.
ohos.net.mdns.DiscoveryServiceoff(type: 'discoveryStart', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): voidDisables listening for discoveryStart events.
ohos.net.mdns.DiscoveryServiceon(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): voidEnables listening for discoveryStop events.
ohos.net.mdns.DiscoveryServiceoff(type: 'discoveryStop', callback?: Callback<{ serviceInfo: LocalServiceInfo, errorCode?: MdnsError }>): voidDisables listening for discoveryStop events.
ohos.net.mdns.DiscoveryServiceon(type: 'serviceFound', callback: Callback<LocalServiceInfo>): voidEnables listening for serviceFound events.
ohos.net.mdns.DiscoveryServiceoff(type: 'serviceFound', callback?: Callback<LocalServiceInfo>): voidDisables listening for serviceFound events.
ohos.net.mdns.DiscoveryServiceon(type: 'serviceLost', callback: Callback<LocalServiceInfo>): voidEnables listening for serviceLost events.
ohos.net.mdns.DiscoveryServiceoff(type: 'serviceLost', callback?: Callback<LocalServiceInfo>): voidDisables listening for serviceLost events.

Managing Local Services

  1. Connect the device to the Wi-Fi network.
  2. Import the mdns namespace from @ohos.net.mdns.
  3. Call addLocalService to add a local service.
  4. (Optional) Call resolveLocalService to resolve the local service for the IP address of the local network.
  5. Call removeLocalService to remove the local service.
// Import the mdns namespace from @ohos.net.mdns.
import mdns from '@ohos.net.mdns';
import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
import featureAbility from '@ohos.ability.featureAbility';
import window from '@ohos.window';

// Construct a singleton object.
export class GlobalContext {
  private constructor() {}
  private static instance: GlobalContext;
  private _objects = new Map<string, Object>();

  public static getContext(): GlobalContext {
    if (!GlobalContext.instance) {
      GlobalContext.instance = new GlobalContext();
    }
    return GlobalContext.instance;
  }

  getObject(value: string): Object|undefined {
    return this._objects.get(value);
  }

  setObject(key: string, objectClass: Object): void {
    this._objects.set(key, objectClass);
  }
}

// Obtain the context of the stage model.
class EntryAbility extends UIAbility {
  value: number = 0;
  onWindowStageCreate(windowStage: window.WindowStage): void{
    GlobalContext.getContext().setObject("value", this.value);
  }
}
let context = GlobalContext.getContext().getObject("value");

class ServiceAttribute {
  key: string = "111"
  value: Array<number> = [1]
}

// Create a LocalService object.
let localServiceInfo: mdns.LocalServiceInfo = {
  serviceType: "_print._tcp",
  serviceName: "servicename",
  port: 5555,
  host: {
    address: "10.14.**.***"
  },
  serviceAttribute: [{key: "111", value: [1]}]
}

// Call addLocalService to add a local service.
mdns.addLocalService(context as Context, localServiceInfo, (error: BusinessError, data: mdns.LocalServiceInfo) =>  {
  console.log(JSON.stringify(error));
  console.log(JSON.stringify(data));
});

// (Optional) Call resolveLocalService to resolve the local service.
mdns.resolveLocalService(context as Context, localServiceInfo, (error: BusinessError, data: mdns.LocalServiceInfo) =>  {
  console.log(JSON.stringify(error));
  console.log(JSON.stringify(data));
});

// Call removeLocalService to remove the local service.
mdns.removeLocalService(context as Context, localServiceInfo, (error: BusinessError, data: mdns.LocalServiceInfo) =>  {
  console.log(JSON.stringify(error));
  console.log(JSON.stringify(data));
});

Discovering Local Services

  1. Connect the device to the Wi-Fi network.
  2. Import the mdns namespace from @ohos.net.mdns.
  3. Create a DiscoveryService object, which is used to discover mDNS services of the specified type.
  4. Subscribe to mDNS service discovery status changes.
  5. Enable discovery of mDNS services on the LAN.
  6. Stop searching for mDNS services on the LAN.
  7. Unsubscribe from mDNS service discovery status changes.
// Import the mdns namespace from @ohos.net.mdns.
import mdns from '@ohos.net.mdns';
import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
import featureAbility from '@ohos.ability.featureAbility';
import window from '@ohos.window';

// Construct a singleton object.
export class GlobalContext {
  private constructor() {}
  private static instance: GlobalContext;
  private _objects = new Map<string, Object>();

  public static getContext(): GlobalContext {
    if (!GlobalContext.instance) {
      GlobalContext.instance = new GlobalContext();
    }
    return GlobalContext.instance;
  }

  getObject(value: string): Object|undefined {
    return this._objects.get(value);
  }

  setObject(key: string, objectClass: Object): void {
    this._objects.set(key, objectClass);
  }
}

// Obtain the context of the stage model.
class EntryAbility extends UIAbility {
  value:number = 0;
  onWindowStageCreate(windowStage: window.WindowStage): void{
    GlobalContext.getContext().setObject("value", this.value);
  }
}

let context = GlobalContext.getContext().getObject("value");

// Create a DiscoveryService object, which is used to discover mDNS services of the specified type.
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context as Context, serviceType);

class DataServiceInfo{
  serviceInfo: mdns.LocalServiceInfo|null = null
  errorCode?: mdns.MdnsError = mdns.MdnsError.INTERNAL_ERROR
}
// Subscribe to mDNS service discovery status changes.
discoveryService.on('discoveryStart', (data: DataServiceInfo) => {
  console.log(JSON.stringify(data));
});
discoveryService.on('discoveryStop', (data: DataServiceInfo) => {
  console.log(JSON.stringify(data));
});
discoveryService.on('serviceFound', (data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});
discoveryService.on('serviceLost', (data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});

// Enable discovery of mDNS services on the LAN.
discoveryService.startSearchingMDNS();

// Stop searching for mDNS services on the LAN.
discoveryService.stopSearchingMDNS();

// Unsubscribe from mDNS service discovery status changes.
discoveryService.off('discoveryStart', (data: DataServiceInfo) => {
  console.log(JSON.stringify(data));
});
discoveryService.off('discoveryStop', (data: DataServiceInfo) => {
  console.log(JSON.stringify(data));
});
discoveryService.off('serviceFound', (data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});
discoveryService.off('serviceLost', (data: mdns.LocalServiceInfo) => {
  console.log(JSON.stringify(data));
});

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Connectivity

harmony 鸿蒙HTTP Data Request

harmony 鸿蒙IPC & RPC Development Guidelines

harmony 鸿蒙IPC & RPC Overview

harmony 鸿蒙Network Connection Management

harmony 鸿蒙Ethernet Connection

harmony 鸿蒙Network Management Overview

harmony 鸿蒙Network Sharing

harmony 鸿蒙Traffic Management

harmony 鸿蒙VPN Management

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/2a12e380fc414756b27c2902f3d9d3d7