Use of the Android network service discovery (NSD) Protocol

Source: Internet
Author: User

Use of the Android network service discovery (NSD) Protocol

Android's Network Service Discovery Protocol (NSD) can be used to discover an application on a nearby device in a small network. This is very helpful for some social networks and multiplayer games.

Android NSD can be used in four ways:

1.Register a network service

2. Network Service Discovery

3.Connect to the network service

4.Log out of the network service


Note the following when using NSD:

Remember to add in ManifestAndroid. permission. INTERNETPermission, or the program will crash.


1. Register a network service

Registering a network service requires two things: the network service information (NsdServiceInfo) and the Registration event listener (NsdManager. RegistrationListener)

After completing these two things, you can use NsdManager. registerService to register the network service. The instance code is as follows:

Public void registerService (View view) {// Note: Do not hard-code the port when registering a network service. Obtain // an available port number for your network service in the following way. int port = 0; try {ServerSocket sock = new ServerSocket (0); port = sock. getLocalPort (); sock. close ();} catch (Exception e) {Toast. makeText (getApplicationContext (), "can not set port", Toast. LENGTH_SHORT);} // register the name, type, port NsdServiceInfo nsdServiceInfo = new NsdServiceInfo (), and nsdServiceInfo of the network service. setServiceName ("NSD_Test_Program"); nsdServiceInfo. setServiceType ("_ http. _ tcp. "); nsdServiceInfo. setPort (port); // registers an event listener for a network service. The Listener object should be saved so that nsRegListener = new NsdManager can be deregistered later. registrationListener () {@ Overridepublic void onUnregistrationFailed (NsdServiceInfo arg0, int arg1) {Toast. makeText (getApplicationContext (), "Unregistration Failed", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onServiceUnregistered (NsdServiceInfo arg0) {Toast. makeText (getApplicationContext (), "Service Unregistered", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onServiceRegistered (NsdServiceInfo arg0) {Toast. makeText (getApplicationContext (), "Service Registered", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onRegistrationFailed (NsdServiceInfo arg0, int arg1) {Toast. makeText (getApplicationContext (), "Registration Failed", Toast. LENGTH_SHORT ). show () ;}}; // obtain the System Network Service Manager. Register NsdManager nsdManager = (NsdManager) getApplicationContext () after preparation (). getSystemService (Context. NSD_SERVICE); nsdManager. registerService (nsdServiceInfo, NsdManager. PROTOCOL_DNS_SD, nsRegListener );}

Note: The registerService () method is executed asynchronously. If you must perform any operation after the service registration is completed, perform these operations in the onServiceResgistered event.


2. Network Service Discovery

To discover a nearby network service, you need to define a network service discovery time listener. The Code is as follows:

Public void discoverService (View view) {nsDicListener = new NsdManager. discoveryListener () {@ Overridepublic void onStopDiscoveryFailed (String serviceType, int errorCode) {Toast. makeText (getApplicationContext (), "Stop Discovery Failed", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onStartDiscoveryFailed (String serviceType, int errorCode) {Toast. makeText (getApplicationContext (), "Start Discovery Failed", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onServiceLost (NsdServiceInfo serviceInfo) {Toast. makeText (getApplicationContext (), "Service Lost", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onServiceFound (NsdServiceInfo serviceInfo) {// This event is triggered when a network service is discovered. // you can use the switch or if command to obtain the services that you really care about. makeText (getApplicationContext (), "Service Found", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onDiscoveryStopped (String serviceType) {Toast. makeText (getApplicationContext (), "Discovery Stopped", Toast. LENGTH_SHORT ). show () ;}@ Overridepublic void onDiscoveryStarted (String serviceType) {Toast. makeText (getApplicationContext (), "Discovery Started", Toast. LENGTH_SHORT ). show () ;}}; NsdManager nsdManager = (NsdManager) getApplicationContext (). getSystemService (Context. NSD_SERVICE); nsdManager. discoverServices ("_ http. _ tcp ", NsdManager. PROTOCOL_DNS_SD, nsDicListener );}


3. connect to the network service

By defining a network service connection time listener to poll the resolved network service, you can further obtain the address and port of the network service and decide whether to connect. Example code:

Public void initResolveListener (View view) {nsResolveListener = new NsdManager. resolveListener () {@ Overridepublic void onServiceResolved (NsdServiceInfo arg0) {// you can obtain the address and port information of the corresponding network service and decide whether to establish a connection with it. // Some socket operations are followed.} @ Overridepublic void onResolveFailed (NsdServiceInfo arg0, int arg1 ){}};}


4. log out of the network service

To log out of a network service, you must save the handle related to the network service in advance and use the NsdManager. unregisterService and NsdManager. stopServiceDiscovery methods to log out of the network service. The instance code is as follows:

Public void unregisterService (View view) {NsdManager nsdManager = (NsdManager) getApplicationContext (). getSystemService (Context. NSD_SERVICE); nsdManager. stopServiceDiscovery (nsDicListener); // disable the network to discover nsdManager. unregisterService (nsRegListener); // deregister the network service}



If reprinted please indicate the source: http://blog.csdn.net/gophers




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.