Skip to content Skip to sidebar Skip to footer

To Write Chat Programming Using Udp And Mqtt Protocol In Android

I am new in Android programming and don't know how to work with UDP and MQTT protocol in android device I want to build an application for chatting android to android device within

Solution 1:

MQTT requires TCP, it is a statefull protocol, you can not implement it with UDP

There is a similar protocol called MQTT-SN which can be implemented with a stateless protocol like UDP.

But both of these are still going to require a broker running somewhere to coordinate the delivery of messages to subscribers to given topics

Solution 2:

I found code to send message on UDP protocol which works as below.

publicclassSendUDPextendsAsyncTask<Void, Void, String> {
    String message;

    publicSendUDP(String message) {
        this.message = message;
    }

    @OverrideprotectedvoidonPreExecute() {
        super.onPreExecute();
    }

    @OverrideprotectedStringdoInBackground(Void[] params) {

        try {
            DatagramSocket socket = newDatagramSocket(13001);
            byte[] senddata = new byte[message.length()];
            senddata = message.getBytes();

            InetSocketAddress server_addr;
            DatagramPacket packet;

            server_addr = newInetSocketAddress(getBroadcastAddress(getApplicationContext()).getHostAddress(), 13001);
            packet = newDatagramPacket(senddata, senddata.length, server_addr);
            socket.setReuseAddress(true);
            socket.setBroadcast(true);
            socket.send(packet);
            Log.e("Packet", "Sent");

            socket.disconnect();
            socket.close();
        } catch (SocketException s) {
            Log.e("Exception", "->" + s.getLocalizedMessage());
        } catch (IOException e) {
            Log.e("Exception", "->" + e.getLocalizedMessage());
        }
        returnnull;
    }

    @OverrideprotectedvoidonPostExecute(String text) {
        super.onPostExecute(text);
    }
}

and below function for fetching broadcast IP address of device connected in the LAN network through which all other devices in the LAN will receive this message.

publicstatic InetAddress getBroadcastAddress(Context context)throws IOException {
    WifiManagerwifi= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    DhcpInfodhcp= wifi.getDhcpInfo();
    // handle null somehowintbroadcast= (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
    byte[] quads = newbyte[4];
    for (intk=0; k < 4; k++)
        quads[k] = (byte) (broadcast >> (k * 8));
    return InetAddress.getByAddress(quads);
}

and this will send UDP message after executing this as

new SendUDP("Hello All Device").execute();

It works like a charm!

Post a Comment for "To Write Chat Programming Using Udp And Mqtt Protocol In Android"