我有一個應用程序可以執行很多操作。我想添加一個方法,使該應用程序的行爲與套接字上的udp服務器相同。特別是它偵聽端口8888上的本地主機地址。我試圖用下面的代碼實現這種行爲,但我得到Address already in use error
。而且整個應用程序都停留在這個udp服務器方法上。我想它可能是由於它的所有運行在一個線程上的事實。udp服務器上的java地址已經在使用錯誤
1)你能告訴我如何糾正我的方法。特別是如何使這個udp服務器監聽器在新線程上啓動。
2)該服務器將永久地聽取來自客戶端的pks。根據服務器是否接收到特定的數據包,它是否需要做某些事情。邏輯是否正確:如果packetReceived爲!= null並且數據包尚未處理,則對其進行處理。永遠重複(如代碼所示)?
public void startSocketListening(){
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket;
System.out.println("Waiting to receive...");
while (true) {
receivePacket = new DatagramPacket(receiveData, receiveData.length);
try {
DatagramSocket serverSocket = new DatagramSocket(8888);
serverSocket.receive(receivePacket);
//if i receive a packet and it doesn't already have a flow rule process it
if ((receivePacket != null) && (newOFRuleAdded == false)){
this.rlocAddress = new String(receivePacket.getData());
System.out.println("RECEIVED: " + rlocAddress);
System.out.println("RLOC: " + rlocAddress);
//process the message
newOFRuleAdded = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
這是不可能的'receivePacket'在你正在測試,通過的Java規則的點都成了空。 – EJP