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.

public class SendUDP extends AsyncTask<Void, Void, String> {
    String message;

    public SendUDP(String message) {
        this.message = message;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void[] params) {

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

            InetSocketAddress server_addr;
            DatagramPacket packet;

            server_addr = new InetSocketAddress(getBroadcastAddress(getApplicationContext()).getHostAddress(), 13001);
            packet = new DatagramPacket(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());
        }
        return null;
    }

    @Override
    protected void onPostExecute(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.

public static InetAddress getBroadcastAddress(Context context) throws IOException {
    WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    DhcpInfo dhcp = wifi.getDhcpInfo();
    // handle null somehow

    int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
    byte[] quads = new byte[4];
    for (int k = 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"