Now you can Subscribe using RSS

Submit your Email

Tuesday

Creating Android chat app using Network Service Discovery(NSD)

Vishal Shrestha
Connecting two devices using NSD in Android
 We will create this Android chat app using NSD in a three part series. In the first part we will learn how to register and broadcast our service on the server device. In the second part we will write the client side code to discover and connect to the server and finally we will complete the code with data transferring capabilities.
http://learnmoneystrategy.com/Vysh01

If you already know this, go to - Part 2.
The following code shows how you can use Network Service Discovery (NSD) to connect two Android devices over a Network. Keep in mind both your Android devices must be connected to the same network.
The NSD API is asynchronous. Listener callbacks on a seperate thread respond to requests from an application. NSD API is very simple. All you need to do is setup service information, register the service. Next, on the client device set up a discovery listener that discovers the services and finally resolve the desired service.

Code in the server device for setting up NSD

  • Set up NSD manager

  • Register Service

  • Setup Registration Listener 

public class NSDMainActivity extends AppCompatActivity {
static final int SocketServerPORT = 8080;  // Port should be fetched dynamically in real systems.// NSD Manager and service registration code
    private String SERVICE_NAME = "Test Server Device";
    private String SERVICE_TYPE = "_http._tcp.";
    private NsdManager mNsdManager;
//Initialize other variable that you will need
 
    ServerSocket serverSocket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Fetch other Components 
        mNsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
        registerService(SocketServerPORT);
   
    }
     };
    
    @Override
    protected void onResume() {
        super.onResume();
        if (mNsdManager != null) {
            registerService(SocketServerPORT);
        }
        
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void registerService(int port) {
        NsdServiceInfo serviceInfo = new NsdServiceInfo();
        serviceInfo.setServiceName(SERVICE_NAME);
        serviceInfo.setServiceType(SERVICE_TYPE);
        serviceInfo.setPort(port);
        
        mNsdManager.registerService(serviceInfo,
            NsdManager.PROTOCOL_DNS_SD,
            mRegistrationListener);
    }
    
    NsdManager.RegistrationListener mRegistrationListener = new NsdManager.RegistrationListener() {

        @Override
        public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
            String mServiceName = NsdServiceInfo.getServiceName();
            SERVICE_NAME = mServiceName;
            Toast.makeText(NSDMainActivity.this, "Successfully registered",
                    Toast.LENGTH_LONG).show();
            Log.d("NsdserviceOnRegister", "Registered name : " + mServiceName);
        }

        @Override
        public void onRegistrationFailed(NsdServiceInfo serviceInfo,
                                  int errorCode) {

            Toast.makeText(NSDMainActivity.this, "registration failed",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
            // NsdManager.unregisterService() called and passed in this listener.
            Log.d("NsdserviceOnUnregister",
                  "Service Unregistered : " + serviceInfo.getServiceName());
        }

        @Override
        public void onUnregistrationFailed(NsdServiceInfo serviceInfo,
                                    int errorCode) {
         //Fail
        }
    };  
} 

That's all. We have registered and broadcasted out service. In the next part we will look at the code for discovering the code in client side. Till then, goodbye and drop down any questions or comments you have. Happy coding.
Part 2 is Published!

Vishal Shrestha / Author & Founder

A developer by profession, a born Adventurer. I mainly do Android but like to get my hands dirty with web development and a little bit of Python. I would't rather go on a Trek than a party and you can find me having a few rounds with the heavy bag to let out the steam ;)

For Business info : My Portfolio Site.

0 comments:

Post a Comment

Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha