我試圖在Java中使用DatagramPacket
和DatagramSocket
類來接收簡單的字符串。Java DatagramPacket和DatagramSocket沒有接收數據
這裏是我的代碼:
public static void main(String [] args){
DatagramSocket aSocket = null;
try{
aSocket= new DatagramSocket();
String aMessage = "my message";
System.out.println("1");
byte [] m = aMessage.getBytes();
InetAddress aHost = InetAddress.getByName("localhost");
int serverPort = 6789;
DatagramPacket request = new DatagramPacket(m,aMessage.length(),aHost,serverPort);
System.out.println("2");
aSocket.send(request);
System.out.println("3");
byte [] buffer = new byte[1000];
System.out.println("4");
DatagramPacket reply = new DatagramPacket(buffer,buffer.length);
aSocket.receive(reply);
System.out.println("5");
System.out.println("DATA RECEIVED" + reply.getData());
aSocket.close();
}
catch(SocketException ex){
ex.printStackTrace();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
它不打印接收到的數據。我已經把System.out.println
只是爲了看代碼在哪裏執行,它停在4,它不打印5,這意味着問題只是在4以下。爲什麼我沒有收到數據,有人可以幫我解決這個問題嗎?
是回覆被*發送*通過什麼代碼?給我們看一看。 – EJP
public static void main(String [] args){ DatagramSocket aSocket = null; 嘗試aSocket = new DatagramSocket(6789); byte [] buffer = new byte [1000]; while(true)DatagramPacket request = new DatagramPacket(buffer,buffer.length); aSocket.receive(request); (), DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(),request.getAddress(),request.getPort()); aSocket.send(reply); (SocketException e){System.out.println(「Socket:」+ e.getMessage()); (IOException e){System.out.println(「IO:」+ e.getMessage());} } } – avi
@arun對不起,我對這個網站很陌生,我找不到如何添加上面的代碼,它現在的工作,錯誤是在我的網絡本身,我也作出了以下答案中指定的datagramsocket的更改。無論如何,我們很幸運有像你這樣的人準備好幫助他人:) – avi