Java UDP数据报无法接收问题求助(Java 9环境)
Hey there! Let's work through why your UDP packets from 10.0.0.3 aren't reaching 10.0.0.6. Since both ends are running similar code, let's start with the most common culprits and step-by-step fixes:
1. Port Mismatch (The #1 Cause!)
UDP relies on matching source/destination ports—if your sender is targeting port X but your receiver is listening on port Y, no packets will get through. Double-check:
- On the receiver side, make sure you're explicitly binding to a specific port when creating the
DatagramSocket:// Receiver must bind to the port the sender is targeting DatagramSocket receiverSocket = new DatagramSocket(1234); - On the sender side, ensure the
DatagramPacketuses the exact same port for the receiver:InetAddress receiverAddr = InetAddress.getByName("10.0.0.6"); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, receiverAddr, 1234);
2. Java 9 Module System Permissions
Java 9's module system can restrict network access if your code is running in a modular context. If you're using a module-info.java file:
- Make sure you've declared the necessary dependencies:
module your.module.name { requires java.base; // Implicitly included, but good to confirm exports your.package.name; // If your main class is in this package } - If you're getting access errors, try adding this JVM argument when launching your app to bypass module restrictions temporarily (for testing):
java --add-opens java.base/java.net=ALL-UNNAMED -jar your-app.jar
3. Firewall/Network Blocking
More often than not, firewalls (local or network-level) block UDP traffic. Test this first to rule out code issues:
- On the receiver machine, run
nc -ul 1234(replace 1234 with your port) to listen for UDP packets. - On the sender machine, run
echo "test" | nc -u 10.0.0.6 1234to send a test packet. - If the receiver doesn't get the test message, you'll need to configure firewalls on both ends to allow UDP traffic on your target port.
4. Code Mistakes to Check
Even small oversights can break UDP delivery:
- Sender: Did you actually call
socket.send(packet)? It's easy to miss this line! Also, ensureInetAddress.getByName("10.0.0.6")doesn't throw an unknown host exception—wrap it in a try-catch and print errors. - Receiver: Are you calling
socket.receive(packet)? This method blocks until a packet arrives, so make sure your receiver isn't exiting before that happens. Also, verify you're reading the correct length of the packet (usepacket.getLength()instead of the full buffer length when converting to a string).
Working Example Code
Here's a stripped-down, tested pair of sender/receiver classes to compare against your code:
Sender (10.0.0.3)
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; public class UDPSender { private static final int TARGET_PORT = 1234; private static final String RECEIVER_IP = "10.0.0.6"; public static void main(String[] args) { try (DatagramSocket socket = new DatagramSocket()) { Scanner scanner = new Scanner(System.in); System.out.println("Type a message to send:"); String message = scanner.nextLine(); byte[] buffer = message.getBytes(); InetAddress receiverAddr = InetAddress.getByName(RECEIVER_IP); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, receiverAddr, TARGET_PORT); socket.send(packet); System.out.println("Packet sent successfully!"); } catch (Exception e) { System.err.println("Error sending packet:"); e.printStackTrace(); } } }
Receiver (10.0.0.6)
import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPReceiver { private static final int LISTEN_PORT = 1234; public static void main(String[] args) { try (DatagramSocket socket = new DatagramSocket(LISTEN_PORT)) { byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); System.out.println("Waiting for UDP packets on port " + LISTEN_PORT + "..."); socket.receive(packet); // Blocks until packet arrives String receivedMsg = new String(packet.getData(), 0, packet.getLength()); System.out.println("Received from " + packet.getAddress().getHostAddress() + ": " + receivedMsg); } catch (Exception e) { System.err.println("Error receiving packet:"); e.printStackTrace(); } } }
Start with the network test using nc—that'll tell you if the issue is with your code or the network. Then work through the port and module checks, and compare against the example code to spot any missing pieces.
内容的提问来源于stack exchange,提问作者parsa

