2016-12-15 53 views
1

我有以下UDP客戶端和服務器類,並且我試圖從UDPClient向本地主機和端口上的相同java項目中的另一個類「UDPServer」發送一些字符串7777.我面臨的問題是,我沒有從UDPClient類的UDPServer類中收到任何內容。有沒有人有問題的地方?UDPServer未收到來自UDPClient的發送數據

我感謝任何幫助!

UDPClient

import java.net.DatagramPacket; 
import java.net.DatagramSocket; 
import java.net.InetAddress; 


class UDPClient { 

    public static void main(String args[]) throws Exception { 
     String aString = "Hello World"; 
     DatagramSocket clientSocket = new DatagramSocket(); 
     InetAddress IPAddress = InetAddress.getByName("localhost"); 
     byte[] sendData = new byte[1024]; 
     byte[] receiveData = new byte[1024]; 
     sendData = aString.getBytes(); 
     DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7777); 
     clientSocket.send(sendPacket); 
     DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
     clientSocket.receive(receivePacket); 
     String modifiedSentence = new String(receivePacket.getData()); 
     System.out.println("FROM SERVER:" + modifiedSentence); 
     clientSocket.close(); 
    } 
} 

UDPServer

import java.net.DatagramPacket; 
import java.net.DatagramSocket; 
import java.net.InetAddress; 


class UDPServer { 

     public static void main(String args[]) throws Exception { 
      DatagramSocket serverSocket = new DatagramSocket(7777); 
      byte[] receiveData = new byte[1024]; 
      byte[] sendData = new byte[1024]; 
      while (true) { 
       DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
       serverSocket.receive(receivePacket); 
       String sentence = new String(receivePacket.getData()); 
       System.out.println("RECEIVED: " + sentence); 
       InetAddress IPAddress = receivePacket.getAddress(); 
       int port = receivePacket.getPort(); 
       String capitalizedSentence = sentence.toUpperCase(); 
       sendData = capitalizedSentence.getBytes(); 
       DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); 
       serverSocket.send(sendPacket); 
      } 
     } 
} 
+0

數據報服務器上的任何異常? – thepaulo

+0

@Sonor否我沒有收到任何錯誤或任何異常。 – water

+0

代碼似乎在我的機器上按預期工作 – scsere

回答

1

嗨嘗試檢查什麼毛病端口分配,因爲你的代碼工作正常。

啓動服務器,並運行此命令:

的Windows

netstat -aon | FINDSTR 7777 

的Linux:

netstat -aon | grep 7777 

您應該看到PID檢查,如果pid是一樣UDPServer上運行。另外檢查防火牆也許有什麼問題嗎?

+0

如果你可以控制你的防火牆,暫時禁用整個防火牆。如果解決了您的問題,則需要爲所有服務器接收傳入數據創建防火牆規則。客戶端應該能夠通過防火牆發送數據而沒有任何問題。 – zooropa

相關問題