I have a bulb and in manual they say that I need send request via UDP. So I create class that send and receive that info what I need. When I try send/obtain request directly from main, studio say that I can't use network from main thread so I put my send/obtain methods to threads. And now I can't understand how I can return any value from thread. Please help. Thanks.
package com.bulbs;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class udpHelper {
public void sendRequest(final String host, final String command, final int port) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
byte[] message = command.getBytes();
try {
InetAddress address = InetAddress.getByName(host);
DatagramPacket packet = new DatagramPacket(message, message.length, address, port);
DatagramSocket dsocket = new DatagramSocket();
dsocket.send(packet);
dsocket.close();
System.out.println("Sent");
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
public void receiveRequest(final int port) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
DatagramSocket dsocket = new DatagramSocket(port);
byte[] buffer = new byte[2048];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
dsocket.receive(packet);
String msg = new String(buffer, 0, packet.getLength());
System.out.println(packet.getAddress().getHostName() + " : " + msg);
packet.setLength(buffer.length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}