Skip to content

Instantly share code, notes, and snippets.

@youweit youweit/gist:7869338
Last active Dec 30, 2015

Embed
What would you like to do?
public class DiscoveryThread implements Runnable {
private static String TAG = "DiscoveryThread";
private DatagramSocket c;
pirvate static Context mContext;
private static int PORT = 5549;
@Override
public void run() {
byte[] bytes = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream daos = new DataOutputStream(baos);
try {
//依照文件好像不應該照這樣寫?XD
daos.write(0);
daos.write(2);
daos.writeShort(0);
daos.writeInt(5549);
daos.writeUTF("AV2000");
daos.writeInt(0);
daos.close();
//total byte size 20
bytes = baos.toByteArray();
Log.d(TAG, bytes.length+"");
} catch (IOException e1) {
e1.printStackTrace();
}
// Find the server using UDP broadcast
try {
// Open a port to send the package
c = new DatagramSocket();
c.setBroadcast(true);
// Broadcast the message over all the network interfaces
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = (NetworkInterface) interfaces
.nextElement();
if (networkInterface.isLoopback() || !networkInterface.isUp()) {
continue; // Don't broadcast to the loopback interface
}
for (InterfaceAddress interfaceAddress : networkInterface
.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null) {
continue;
}
// Send the broadcast package!
try {
DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, broadcast, PORT);
c.send(sendPacket);
} catch (Exception e) {
}
Log.d(TAG,
getClass().getName()
+ "Request packet sent to: /"
+ broadcast.getHostAddress()
+ "; Interface: "
+ networkInterface.getDisplayName());
}
}
Log.d(TAG,
getClass().getName()
+ "Waiting for a reply!");
// Wait for a response
byte[] recvBuf = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(recvBuf,
recvBuf.length);
c.receive(receivePacket);
// Have a response
Log.d(TAG, getClass().getName()
+ "Broadcast response from: "
+ receivePacket.getAddress().getHostAddress());
// Check if the message is correct
String message = new String(receivePacket.getData()).trim();
if (message.equals("DISCOVER_FUIFSERVER_RESPONSE")) {
// DO SOMETHING...
}
// Close the port!
c.close();
} catch (IOException ex) {
}
}
public static DiscoveryThread getInstance(Context c) {
mContext = c;
return DiscoveryThreadHolder.INSTANCE;
}
private static class DiscoveryThreadHolder {
private static final DiscoveryThread INSTANCE = new DiscoveryThread();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.