Creating Android chat app using Network Service Discovery(NSD)

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.

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!

Don’t miss these tips!

We don’t spam! Read our privacy policy for more info.

You’ve been successfully subscribed to our newsletter! See you on the other side!

Sharing is caring!

7 thoughts on “Creating Android chat app using Network Service Discovery(NSD)”

  1. I'm not one of those readers that comments on articles often, but yours really compelled me. There's a lot of interesting content in this article that is interesting and bold. Chatous is a free random chat website, that connects users from all over the world. These websites like Chatous allow users to chat with strangers and meet new people online. Chat us websites like Talk with stranger or Chatous offer many different chat rooms for all users. You can even join anonymously and exchange texts and pictures with random people online on talkwithstranger.

  2. VarangaOfficial – варанга производитель – проверенные и достоверные факты. Воспользовавшись нашим онлайн-сервисом, вы сможете узнать исчерпывающую информацию касательно этого натурального лекарственного комплекса. Лично увидеть данные о проведенных клинических исследований, прочесть реальные отзывы пациентов и врачей, использующих крем в своей лечебной практике. Ознакомиться с инструкцией по применению, прочесть особенности и методы работы мази, уяснить, почему крем Варанга настолько эффективен, где можно приобрести оригинальный сертифицированный препарат и, как не нарваться на фальсифицированный товар. Мы очень тщательно проверяем размещаемые на сайте данные. Предоставляем посетителям нашего онлайн-ресурса сведения, взятые только из подлинных источников. Если вы нашли у себя признаки развития грибка или же долго и безрезультатно пытаетесь излечиться от этого коварного, неприятного недуга, у нас на сайте вы найдете быстрый и простой способ устранения проблемы. Приобщайтесь и живите здоровой полноценной жизнью. Теперь все ответы на самые популярные и волнующие пользователей вопросы, собраны на одном ресурсе.

  3. I just had to show my appreciation for the writer's point of view on this subject by leaving a comment. Thank you for writing such top notch content for your readers. Thank you so much. Do you want to have a free chat now? Regardless of whether you're an explorer new to the mysterious universe of free online chatting or somebody basically hoping to more readily mingle among new people. Free chat now on talkwithstranger. A platform that welcomes you to explore free chat, talk or text without caring about being judged or recognized.

  4. Free chat now allows two users to connect with each other in a chat room where they can start a chat now without registration. Free chat now with anyone without revealing your identity. So what are you waiting for, start a free chat now. Free chat now is a chat room that is free and where you can find millions of people from around the world to chat with. Get connected with amazing people and start the free chat now. Free chat rooms are very popular nowadays and let users have a great chatting experience. Users love these chat rooms because the best thing about them is that they are free and allow the users to chat about whatever they want.

  5. Very resourceful article has been dropped here. You have focused on the whole research methodology and literature content in an excellent way. I was impressed . This is really very good and fantastic to learn. Thanks a lot for sharing information about Free Online Voice Chat With Strangers. Also I would like to put a site that is related to this topic hoping many readers here are looking for more ideas regarding this. Here are methodology dissertation May be helpful for you.

  6. I looked on you web to discover more with regards to the issue aand observed most people will oblige your perspectives on this web site.| Hello, I sign on tto your online journals like consistently. Your composing style is clever, keep it up!| I basically couldn't leave youwebsitee befire recommending that I truly adored the standard data aan individual inventory in your visitors? Free chat now allows two users to connect with each other in a chat room where they can start a chat now without registration. free chat now with anyone without revealing your identity. So what are you waiting for, start a free chat now?

Leave a Comment

Your email address will not be published.

Exit mobile version