# Titanium.Network.BonjourService

Describes a service on the network which is published by Bonjour.

Availability
1.2.0
9.2.0

# Overview

You can obtain a BonjourService instance by calling Titanium.Network.createBonjourService or from the service list from a Titanium.Network.BonjourBrowser
updatedservices event.

You can only publish Bonjour services attached to a socket which is currently listening; you cannot publish a service for a remotely connected socket. If you stop the Bonjour service and wish to close the socket it uses, it is strongly recommended that you stop the service first. When a window which publishes a Bonjour service is closed, you must stop the service if the associated socket is also to be closed, or if it is no longer necessary to publish. Bonjour service resolution and publishing is asynchronous.

In iOS 14.0+, to publish service add key NSLocalNetworkUsageDescription and NSBonjourServices in tiapp.xml file.

Example:

<ti:app>
  <!-- ... -->
  <ios>
    <plist>
      <dict>
        <!-- Reason to access local network-->
        <key>NSLocalNetworkUsageDescription</key>
        <string>
            Specify the reason for accessing the local network.
            This appears in the alert dialog when asking the user 
            for permission to access local network.
        </string>
        <!-- List of bonjour service type-->
        <key>NSBonjourServices</key>
        <array>
          <string>_test._tcp</string>
        <array/>
      </dict>
    </plist>
  </ios>
  <!-- ... -->
</ti:app>

# Examples

# Resolve local HTTP/TCP services

The following code excerpt looks for http-based TCP zeroconf services on the local network. It then attempts to resolve the service, establishing a socket that can be used for communications.

// Create the Bonjour Browser (looking for http)
var httpBonjourBrowser = Ti.Network.createBonjourBrowser({
  serviceType: '_http._tcp',
  domain: 'local'
});

// Handle updated services
httpBonjourBrowser.addEventListener('updatedservices', function (e) {
  for (var service of e.services) {
      // callback style
      service.resolve(120, (err, success) => {
          console.log(service.socket);
          console.log(service.socket.port);
          console.log(service.socket.host);
      });
  }
});

// Start searching
httpBonjourBrowser.search();

# Create and Publish a local HTTP/TCP service

The following code excerpt creates a zeroconf bonjour service and publishes it out to the local network. A TCP Socket is used to handle listening for clients and communicating.

// Create the Bonjour Service
var localService = Ti.Network.createBonjourService({
  name: 'example',
  type: '_test._tcp',
  domain: 'local.'
});

// Create the socket we'll tie to the service
var bonjourSocket = Ti.Network.Socket.createTCP({
  host: '127.0.0.1',
  port: 40401,
  accepted: function (e) {
    // Here you handle clients connecting
    Ti.API.info("Listening socket <" + e.socket + "> accepted incoming connection <" + e.inbound + ">");
    e.inbound.write(Ti.createBuffer({
      value: 'You have been connected to a listening socket.\r\n'
    }));
    e.inbound.close();
  },
  error: function (e) {
    // handle errors...
    Ti.API.error("Socket <" + e.socket + "> encountered error when listening");
    Ti.API.error(" error code <" + e.errorCode + ">");
    Ti.API.error(" error description <" + e.error + ">");
  }
});

// Make the socket listen for connections
bonjourSocket.listen();

// Make the socket accept incoming connections
bonjourSocket.accept({ timeout: 10000 });

// Publish the service
localService.publish(bonjourSocket, fnction (err, bool) {
  // Now you can find the service on your network (including using a Ti.Network.BonjourBrowser)
});

# Properties

# apiName READONLY

Availability
3.2.0
9.2.0
apiName :String

The name of the API that this proxy corresponds to.

The value of this property is the fully qualified name of the API. For example, Titanium.UI.Button returns Ti.UI.Button.


# bubbleParent

Availability
3.0.0
9.2.0
bubbleParent :Boolean

Indicates if the proxy will bubble an event to its parent.

Some proxies (most commonly views) have a relationship to other proxies, often established by the add() method. For example, for a button added to a window, a click event on the button would bubble up to the window. Other common parents are table sections to their rows, table views to their sections, and scrollable views to their views. Set this property to false to disable the bubbling to the proxy's parent.

Default: true


# domain

Availability
1.2.0
9.2.0
domain :String

the domain of the service


# isLocal

Availability
1.2.0
9.2.0
isLocal :Boolean

whether or not the service is local to the device

Default: true


# name

Availability
1.2.0
9.2.0
name :String

the name of the service


# socket

Availability
1.2.0
9.2.0

the TCPSocket object that is used to connect to the service


# type

Availability
1.2.0
9.2.0
type :String

the type of the service

# Methods

# addEventListener

Availability
1.2.0
9.2.0
addEventListener(name, callback) void

Adds the specified callback as an event listener for the named event.

Parameters

Name Type Description
name String

Name of the event.

callback Callback<Titanium.Event>

Callback function to invoke when the event is fired.

Returns

Type
void

# applyProperties

Availability
3.0.0
9.2.0
applyProperties(props) void

Applies the properties to the proxy.

Properties are supplied as a dictionary. Each key-value pair in the object is applied to the proxy such that myproxy[key] = value.

Parameters

Name Type Description
props Dictionary

A dictionary of properties to apply.

Returns

Type
void

# fireEvent

Availability
1.2.0
9.2.0
fireEvent(name[, event]) void

Fires a synthesized event to any registered listeners.

Parameters

Name Type Description
name String

Name of the event.

event Dictionary

A dictionary of keys and values to add to the Titanium.Event object sent to the listeners.

Returns

Type
void

# publish

Availability
1.2.0
9.2.0
publish(socket[, callback]) void

Asynchronously publish a Bonjour service to the network. Only works if isLocal is TRUE

Parameters

Name Type Description
socket Titanium.Network.Socket.TCP

a TCPSocket object to associate with the Bonjour service.

callback Callback<Error, Boolean>

Asynchronous callback function to receive the result of the publish operation

Returns

Type
void

# removeEventListener

Availability
1.2.0
9.2.0
removeEventListener(name, callback) void

Removes the specified callback as an event listener for the named event.

Multiple listeners can be registered for the same event, so the callback parameter is used to determine which listener to remove.

When adding a listener, you must save a reference to the callback function in order to remove the listener later:

var listener = function() { Ti.API.info("Event listener called."); }
window.addEventListener('click', listener);

To remove the listener, pass in a reference to the callback function:

window.removeEventListener('click', listener);

Parameters

Name Type Description
name String

Name of the event.

callback Callback<Titanium.Event>

Callback function to remove. Must be the same function passed to addEventListener.

Returns

Type
void

# resolve

Availability
1.2.0
9.2.0
resolve([timeout[, callback]]) void

Asynchronously resolve a Bonjour service from the network. Must be done before attempting to access the service's socket information, if a remote service. You cannot resolve a locally published service.

Parameters

Name Type Description
timeout Number

the timeout for service resolution, in seconds. Optional, default is 120s.

callback Callback<Error, Boolean>

Asynchronous callback function to receive the result of the resolve operation

Returns

Type
void

# stop

Availability
1.2.0
9.2.0
stop([callback]) void

Asynchronously halts a currently running attempt to publish or resolve a service.

Parameters

Name Type Description
callback Callback<Error, Boolean>

Asynchronous callback function to receive the result of the stop operation

Returns

Type
void

# Events

# publish

Availability
1.2.0
9.2.0

Fired when the service has been published (or errored).

Properties

Name Type Description
code Number

Error code

error String

Error message

success Boolean

Reports if the publish operation was successful

source Titanium.Network.BonjourService

the service whose publish operation was completed/errored.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# resolve

Availability
1.2.0
9.2.0

Fired when the service has been resolved (or errored). If successful, the socket property should now be available.

Properties

Name Type Description
code Number

Error code

error String

Error message

success Boolean

Reports if the resolve operation was successful

source Titanium.Network.BonjourService

the service whose resolve operation was completed/errored.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.


# stop

Availability
1.2.0
9.2.0

Fired when a service's publish or resolution was stopped via stop

Properties

Name Type Description
code Number

Error code

error String

Error message

success Boolean

Reports if the stop operation was successful

source Titanium.Network.BonjourService

the service whose publish or resolve operation was stopped.

source Object

Source object that fired the event.

type String

Name of the event fired.

bubbles Boolean

True if the event will try to bubble up if possible.

cancelBubble Boolean

Set to true to stop the event from bubbling.