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!

Comments

  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.

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

    ReplyDelete
  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.

    ReplyDelete

Post a Comment