餐盘柜优化
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
package com.sw.platecabinet.socket;
|
||||
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
|
||||
/**
|
||||
* Simple UDP discovery client:
|
||||
* Sends "DISCOVER_SERVER" broadcast and waits for first reply "SERVER_FOUND:serverName:ip"
|
||||
*/
|
||||
public class UdpDiscoveryClient {
|
||||
|
||||
public interface Listener {
|
||||
void onFound(String ip, String serverName);
|
||||
|
||||
void onError(Exception e);
|
||||
}
|
||||
|
||||
public void discover(int discoveryPort, int timeoutMs, Listener listener) {
|
||||
new Thread(() -> {
|
||||
try (DatagramSocket socket = new DatagramSocket()) {
|
||||
socket.setBroadcast(true);
|
||||
byte[] data = "DISCOVER_SERVER".getBytes();
|
||||
DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("255.255.255.255"), discoveryPort);
|
||||
socket.send(packet);
|
||||
|
||||
socket.setSoTimeout(timeoutMs);
|
||||
byte[] buf = new byte[512];
|
||||
DatagramPacket resp = new DatagramPacket(buf, buf.length);
|
||||
socket.receive(resp);
|
||||
|
||||
String msg = new String(resp.getData(), 0, resp.getLength());
|
||||
if (msg.startsWith("SERVER_FOUND")) {
|
||||
// format: SERVER_FOUND:serverName:ip
|
||||
String[] parts = msg.split(":", 3);
|
||||
if (parts.length >= 3) {
|
||||
listener.onFound(parts[2], parts[1]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
listener.onError(new Exception("Invalid response"));
|
||||
} catch (Exception e) {
|
||||
listener.onError(e);
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user