2011-04-29 268 views
0

嗨,我有一個udp客戶端服務器代碼不工作我問一個普遍的問題「Shane是一個很好的孩子」兩個代碼都沒有出現錯誤,但是當我運行代碼時,它輸出 DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,9876);而不是讓客戶問候服務器。流程應該是Server初始化等客戶機 - 客戶機問候服務器 - 服務器問題 - 客戶機回答問題 - 服務器統計是否投票和顯示天氣或不是人= =。 如何圓代碼的任何建議將受到歡迎 聽到的是服務器端的代碼客戶端服務器udp套接字

import java.net.*; 

public class VotingServer { 
//private static final int yes = 0; 
private static int yes2; 

public static void main(String[] args, int getrep) throws Exception{ 
    // part 1: initialization 
    DatagramSocket serverSocket = new DatagramSocket(9876); 
    byte[] receiveData = new byte[1024]; 
    byte[] sendData = new byte[1024]; 
    InetAddress[] IPAddressList = new InetAddress[5]; 
    int[] portList = new int[5]; 

    // part 2: receive the greeting from clients 
    for (int i=0; i<1; i++) { 
     DatagramPacket receivePacket = 
      new DatagramPacket(receiveData, receiveData.length); 
     serverSocket.receive(receivePacket); 
     String greeting = new String(receivePacket.getData()); 
     System.out.println("From Client: " + greeting); 

     IPAddressList[i] = receivePacket.getAddress(); 
     portList[i] = receivePacket.getPort(); 
    } // for (i) 

    // part 3: broadcast the votiong question to all clients 
    String question = "is shane a good kid 1 for yes 0 no?\n"; 
    for (int i=0; i<5; i++) { 
     sendData = question.getBytes(); 
     DatagramPacket sendPacket = 
      new DatagramPacket(sendData, sendData.length); 
     serverSocket.send(sendPacket); 

    // part 5: receive the age of client (B) 
     DatagramPacket receivePacket = 
      new DatagramPacket(receiveData, receiveData.length); 
     serverSocket.receive(receivePacket); 
     String ageStr = new String(receivePacket.getData()); 
     yes2 = Integer.parseInt(ageStr); 

     IPAddressList[i] = receivePacket.getAddress(); 
     portList[i] = receivePacket.getPort(); 

    // part 6: compute the price (C) 
    double count= 0; 
    double no = 0; 

    if (yes2 >= 1) count = 1; 
    else 
     if (yes2 <= 0) no = 1; 

    // part 7: send the price to client 
    String rep = null; 
    String countStr = ""+count+"\n"; 
    String noStr = ""+no+"\n"; 
    if (no < count) rep = "Is a good kid"; 
    else 
     if (no > count) rep = "is a bad kid"; 
    System.out.println(" "+getrep); 
    sendData = countStr.getBytes(); 
    sendData = noStr.getBytes(); 
    sendData = rep.getBytes(); 
    DatagramPacket sendPacket1 = 
     new DatagramPacket(sendData, sendData.length); 
    serverSocket.send(sendPacket1); 

} // main() 

}} // UDPServer 

這裏是客戶端代碼 進口java.io. ; import java.net。;

public class ClientVoting { 

    public static void main(String[] args) throws Exception { 
     // part 1: initialization 
     BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
     DatagramSocket clientSocket = new DatagramSocket(); 
     InetAddress IPAddress = InetAddress.getByName("localhost"); 
     byte[] sendData = new byte[1024]; 
     byte[] receiveData = new byte[1024]; 



     String sentence = inFromUser.readLine(); 
     sendData = sentence.getBytes(); 
     DatagramPacket sendPacket = 
      new DatagramPacket(sendData, sendData.length, IPAddress, 9876); 
     clientSocket.send(sendPacket); 


     // part 2: receive the question from server 
     DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
     clientSocket.receive(receivePacket); 
     String question = new String(receivePacket.getData()); 
     System.out.println("From Server:" + question); 

     String yes2 = inFromUser.readLine(); 
     sendData = yes2.getBytes(); 
     DatagramPacket sendPacket1 = 
      new DatagramPacket(sendData, sendData.length, IPAddress, 9876); 
     clientSocket.send(sendPacket1); 


     // part 4: get the price from server 
     receivePacket = new DatagramPacket(receiveData, receiveData.length); 
     clientSocket.receive(receivePacket); 
     String rep = new String(receivePacket.getData()); 
     System.out.println("the answer is " + rep); 

     // part 4: close the socket 
     clientSocket.close(); 

    } // main() 

    } // class UDPClient 

由於SPF

回答

1

我得到運行在服務器端代碼中的NullPointException ......還有在代碼本身的一些問題。第一個是您試圖保留客戶端連接實例的數組的索引。在這一點上,你只有一個...

for (int i=0; i<1; i++) { 
    DatagramPacket receivePacket = 
     new DatagramPacket(receiveData, receiveData.length); 
    serverSocket.receive(receivePacket); 
    String greeting = new String(receivePacket.getData()); 
    System.out.println("From Client: " + greeting); 

    IPAddressList[i] = receivePacket.getAddress(); 
    portList[i] = receivePacket.getPort(); 
} // for (i) 

然而,在這一點上,你的代碼很容易出現NullPointException當你試圖遍歷5次......

String question = "is shane a good kid 1 for yes 0 no?\n"; 
for (int i=0; i<5; i++) { 
    sendData = question.getBytes(); 
    DatagramPacket sendPacket = 
     new DatagramPacket(sendData, sendData.length); 
    serverSocket.send(sendPacket); <<<<---- NPE prone code line... 

這裏的運行代碼的結果......

From Client: hello 
Exception in thread "main" java.lang.NullPointerException: null buffer || null address 
    at java.net.PlainDatagramSocketImpl.send(Native Method) 
    at java.net.DatagramSocket.send(DatagramSocket.java:629) 
    at com.vasoftware.sf.common.VotingServer.main(VotingServer.java:38) 

看着這個例外,我注意到,因爲你的緩衝就不會是空,你的地址是一個問題,因爲你創建一個新的DatagramPacket沒有IP和客戶端連接的端口號......您必須將它們傳遞到DatagramPacket實例,以便服務器知道誰是客戶端嘗試通信的內容......您想要實現的一個非常簡單/基本的示例是http://systembash.com/content/a-simple-java-udp-server-and-udp-client/ 。下面是我最初的代碼修復...你的答案仍然需要緩衝區的一些工作,我將它作爲一個練習...

這裏是固定代碼的服務器,只接受1客戶..我將離開多線程的東西+你作爲一個練習的數據處理程序...

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

public class VotingServer { 

    //private static final int yes = 0; 
    private static int yes2; 

    public static void main(String[] args) throws Exception { 
     // part 1: initialization 
     DatagramSocket serverSocket = new DatagramSocket(9876); 
     byte[] receiveData = new byte[1024]; 
     byte[] sendData = new byte[1024]; 
     InetAddress IPAddressList; 
     int portList = -1; 

     // part 2: receive the greeting from clients 
     System.out.println("Ready to receive connections at port " + serverSocket.getLocalPort()); 
     DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
     serverSocket.receive(receivePacket); 
     String greeting = new String(receivePacket.getData()); 
     System.out.println("From Client: " + greeting); 

     IPAddressList = receivePacket.getAddress(); 
     portList= receivePacket.getPort(); 

     // part 3: broadcast the votiong question to all clients 
     String question = "is shane a good kid 1 for yes 0 no?\n"; 
     sendData = question.getBytes(); 
     DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddressList, portList); 
     serverSocket.send(sendPacket); 

    // part 5: receive the age of client (B) 
     receiveData = new byte[1024]; 
     receivePacket = new DatagramPacket(receiveData, receiveData.length); 
     serverSocket.receive(receivePacket); 
     String ageStr = new String(receivePacket.getData()); 

     try { 
      yes2 = Integer.parseInt(ageStr); //<<<----- WILL NEVER GET THE VALUE... LEAVING IT AS AN EXERCISE.... 

     } catch (NumberFormatException nfe) { 
      yes2 = 0; 
     } 

     receivePacket.getAddress(); 
     receivePacket.getPort(); 

     // part 6: compute the price (C) 
     double count= 0; 
     double no = 0; 

     if (yes2 >= 1) count = 1; 
     else 
      if (yes2 <= 0) no = 1; 

     // part 7: send the price to client 
     // ALSO FIXING SOME CODE HERE AS WELL.... 
     String rep = null; 
     rep = no < count ? "Is a good kid" : "is a bad kid"; 
     rep += " Server Count: " + count; 

     sendData = rep.getBytes(); 
     DatagramPacket sendPacket1 = new DatagramPacket(sendData, sendData.length, IPAddressList, portList); 
     serverSocket.send(sendPacket1); 
    } 
} 

這裏的客戶端:

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.net.DatagramPacket; 
import java.net.DatagramSocket; 
import java.net.InetAddress; 

public class ClientVoting { 

    public static void main(String[] args) throws Exception { 
     // part 1: initialization 
     BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
     DatagramSocket clientSocket = new DatagramSocket(); 
     InetAddress IPAddress = InetAddress.getByName("localhost"); 
     byte[] sendData = new byte[1024]; 
     byte[] receiveData = new byte[1024]; 

     System.out.print("What's the question? "); 
     String sentence = inFromUser.readLine(); 
     sendData = sentence.getBytes(); 
     System.out.println("Attempting to connect the server at port " + 9876); 
     DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); 
     clientSocket.send(sendPacket); 

     System.out.println("Initial greeting sent... Waiting for response..."); 

     // part 2: receive the question from server 
     DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
     clientSocket.receive(receivePacket); 
     String question = new String(receivePacket.getData()); 
     System.out.println("From Server:" + question); 

     String yes2 = inFromUser.readLine(); 
     sendData = yes2.getBytes(); 
     DatagramPacket sendPacket1 = 
      new DatagramPacket(sendData, sendData.length, IPAddress, 9876); 
     clientSocket.send(sendPacket1); 


     // part 4: get the price from server 
     receiveData = new byte[1024]; 
     receivePacket = new DatagramPacket(receiveData, receiveData.length); 
     clientSocket.receive(receivePacket); 
     String rep = new String(receivePacket.getData()); 
     System.out.println("the answer is " + rep); 

     // part 4: close the socket 
     clientSocket.close(); 

    } // main() 
} 

必須先執行服務器,因爲它將偵聽端口9876上打開的套接字。然後,您可以使用客戶端連接到服務器。

###### Here's the output in the server-side... Just added a few details of what's going on... 
Ready to receive connections at port 9876 
From Client: Marcello 

####### Here's the output of the client: 
What's the question? Marcello 
Attempting to connect the server at port 9876 
Initial greeting sent... Waiting for response... 
From Server:is shane a good kid 1 for yes 0 no? 
the answer is is a bad kid Server Count: 0.0 

,因爲它似乎是你的要求是設計一個服務器,它可以處理多個客戶端和投票數算,我也建議您使用不同的線程使用的服務器的多線程版本在自己的線程中處理每個客戶端並更新靜態計數器的值(例如,執行新的Runnable的例子是一個while(true)循環,這裏的執行器是http://java-x.blogspot.com/2006/11/java-5-executors-threadpool.html)。考慮如上所述創建一個Runnable實例,並將服務器的代碼放置在public void run(){}方法實現中......我將把它作爲一個練習,以供您參考......