我的项目由一个用java编写的服务器和一个用python编写并在raspberry上运行的客户端组成。
我正在尝试发送带有覆盆子pi的广播UDP消息,以便在我的网络中查找服务器(其IP地址随时间更改,因此我默认情况下无法设置),以便只有服务器才会回答根据我的要求,我可以获得其IP。
我的客户端代码非常简单:
import socket
import ssl
PORT=4435
sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto("SERVER?", ("<broadcast>", PORT))
print(sock.recv(4096))
sock.close()
它只是打开一个套接字并发送消息“SOCKET?”在广播中。
服务器也是如此。 “服务器”类:
public class Server extends Thread {
private ServerSocket server;
public ServerBroadcast() {
try{
this.server= new ServerSocket(4435);
System.out.println("Server is active");
this.start();
} catch (Exception e) {
System.out.println(e);
}
}
public void run() {
try {
System.out.println("Broadcast server is active!");
while (true) {
Socket richiestaClient = this.serverSocket.accept();
System.out.println("received");
new GestioneRichiesteBroadcast(richiestaClient);
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
班级“GestioneRichiesteBroadcast”: 公共课GestioneRichiesteBroadcast {
private Socket connessione;
private Scanner input;
private PrintStream output;
private Date data;
private DateFormat formatoData;
public GestioneRichiesteBroadcast(Socket client) {
try {
this.connessione = client;
this.input = new Scanner(client.getInputStream());
this.output = new PrintStream(client.getOutputStream());
this.data = new Date();
this.formatoData = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
this.gestioneRichiesta();
} catch (IOException e) {
System.out.println(e);
}
}
public void gestioneRichiesta() {
String messaggio = this.input.nextLine();
if (messaggio.contentEquals("SERVER?")) {
this.output.println("YES,"+this.formatoData.format(this.data));
}
}
}
我的服务器没有看到客户端发送的消息,但Wireshark捕获它们并正确显示它们。我错了什么?