I am facing a weird issue, I have written an app for Android by following Google Blog.
Here is the code snippet:
Server:
protected DatagramSocket createSocket() throws UnknownHostException, IOException {
if (mSocket == null) {
DatagramChannel mChannel = DatagramChannel.open();
mSocket = mChannel.socket();
mSocket.setReuseAddress(true);
mSocket.setBroadcast(true);
mSocket.bind(new InetSocketAddress(PORT));
}
return mSocket;
}
[Broadcasting Inside While loop Thread]
private void startBroadcast(String message) throws IOException {
byte[] data = message.getBytes();
DatagramPacket packet = new DatagramPacket(
data,
data.length,
mBroadcastAddress,
mBroadcastPort
);
mSocket.send(packet);
}
Client:
protected DatagramSocket createSocket() throws IOException {
if (mSocket == null) {
DatagramChannel mChannel = DatagramChannel.open();
mSocket = mChannel.socket();
mSocket.setReuseAddress(true);
mSocket.setSoTimeout(10000);
mSocket.bind(new InetSocketAddress(PORT));
}
return mSocket;
}
protected void receiveIntents() throws IOException {
while (running) {
DatagramPacket packet = new DatagramPacket(
new byte[MAXIMUM_PACKET_BYTES], MAXIMUM_PACKET_BYTES
);
mSocket.receive(packet);
byte[] data = packet.getData();
int length = packet.getLength();
String msg = new String(data, 0, length);
listener.onBroadCastResponseReceived(packet.getAddress(), msg);
}
}
I have debugged the code and found that the Server is working fine and broadcasting messages on time. But the Client is blocking on "mSocket.receive(packet);". If I switch the WiFi connection On/Off it starts receiving message on the same socket instantly.