问题
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 room connected to same Wi-Fi router.
But I don't know what IP address and port I should bind to DatagramSocket and DatagramPacket.
I tried lot of examples from online but I didn't understand how it will work in android.
回答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
回答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!
来源:https://stackoverflow.com/questions/38627871/to-write-chat-programming-using-udp-and-mqtt-protocol-in-android