2013-10-22 3 views
0

자, 다음은 간단한 TFTP (Trivial File Transfer Protocol) 프로그램을 만드는 데 사용하는 2 개의 클래스입니다. 이 프로그램의 서버 인스턴스와 클라이언트 인스턴스를 실행하고 있습니다. 내가 성취하려고하는 것은 다음과 같습니다.java.lang.NumberFormatException : null in Integer.parseInt

클라이언트는 서버에 연결하여 원하는 특정 파일의 메시지를 보냅니다. 서버는 파일을 찾고 응답을 보냅니다 (1 또는 0 ... 1은 파일이 있음을 의미하고 0은 응답 없음). 그런 다음 서버는 파일 내용을 클라이언트 응용 프로그램으로 보냅니다. 보낼 파일은 단순한 텍스트 파일입니다.

지금 당장은 클라이언트가 원하는 텍스트 파일의 이름을받을 수 있지만 응답을 다시 보내면 반환되는 내용이 없습니다. 또한 아래에는 서버와 클라이언트가 모두 실행되는 방법이 나와 있습니다.

서버 인스턴스

SwingUtilities.invokeLater(new Runnable(){ 
    public void run(){ 
     String fileRequest = UDPReceiver(SERVER_PORT_NUMBER); 
     outputArea.append("\n" + "File Requested: " + fileRequest + "\n"); 
     outputArea.append("Determining if file exists...\n"); 
     String checkFile = SHARED_DIR + "\\" + fileRequest; 
     outputArea.append("Checking location: " + checkFile + "\n"); 

     boolean check = fileCheck(checkFile); 
     if(check == true){ 
      outputArea.append("File location verified..." + "\n"); 
      outputArea.append("Initiating transfer...." + "\n\n"); 

      UDPSender(CLIENT_HOSTNAME, CLIENT_PORT_NUMBER, "1"); 

      } 
      else{ 
       outputArea.append("File does not exist..." + "\n"); 
       outputArea.append("Exiting run..." + "\n"); 
      } 
     } 
    }); 

클라이언트 인스턴스입니다.

SwingUtilities.invokeLater(new Runnable(){ 
    public void run(){ 
     UDPSender(SERVER_HOSTNAME, SERVER_PORT_NUMBER, FILE_REQUEST); 

     String message = UDPReceiver(CLIENT_PORT_NUMBER); 
     outputArea.append("\n\n" + message + "\n"); 

     if(message == "1"){ 
      // File exists 
      outputArea.append("\n"); 
      outputArea.append("File verified..." + "\n"); 
      outputArea.append("Transfer initiated..." + "\n"); 
     } 
     else{ 
      // File doesn't exist 
      outputArea.append("\n"); 
      outputArea.append("File does not exist..." + "\n"); 
      outputArea.append("Terminating connection..."); 
     } 
    } 
}); 

다음은 송신자 및 수신자 메소드입니다.

private void UDPSender(String hostname, String port, String message){ 
    DatagramSocket socket = null; 
    try{ 
     // Create a datagram socket, look for the first available port 
     socket = new DatagramSocket(); 

     outputArea.append("Using local port: " + socket.getLocalPort() + "\n"); 
     ByteArrayOutputStream bOut = new ByteArrayOutputStream(); 
     PrintStream pOut = new PrintStream(bOut); 
     pOut.print(message); 
     // Convert printstream to byte array 
     byte[] bArray = bOut.toByteArray(); 
     // Create a DatagramPacket, containing a maximum buffer of 256 bytes 
     DatagramPacket packet = new DatagramPacket(bArray, bArray.length); 

     outputArea.append("Looking for hostname " + hostname + "\n"); 
     // Get the InetAddress object 
     InetAddress remote_addr = InetAddress.getByName(hostname); 
     // Check its IP Number 
     outputArea.append("Hostname has IP Address = " + remote_addr.getHostAddress() + "\n"); 
     // Configure the DatagramPacket 
     packet.setAddress(remote_addr); 
     packet.setPort(Integer.parseInt(port)); 
     // Send the packet 
     socket.send(packet); 
     outputArea.append("Packet sent at: " + new Date() + "\n"); 

     // Display packet information 
     outputArea.append("Sent by: " + remote_addr.getHostAddress() + "\n"); 
     outputArea.append("Sent from: " + packet.getPort() + "\n"); 
     socket.close(); 
    } 
    catch(UnknownHostException ue){ 
     outputArea.append("Unknown host: " + hostname + "\n"); 
     outputArea.append("Unknown host: " + ue + "\n"); 
    } 
    catch(IOException e){ 
     outputArea.append("Error: " + e + "\n"); 
    } 
} 


private String UDPReceiver(String portNum){ 
    String message = ""; 
    DatagramSocket socket = null; 
    try{ 
     // Create a DatagramSocket 
     socket = new DatagramSocket(Integer.parseInt(portNum)); 

     outputArea.append("Listening on local port " + socket.getLocalPort() + "\n"); 

     // Create a DatagramPacket, containing a maximum buffer of 256 bytes 
     DatagramPacket packet = new DatagramPacket(new byte[256], 256); 

     // Receive a packet - remember by default this is a blocking operation 
     socket.receive(packet); 

     outputArea.append("Packet received at " + new Date() + "\n"); 
     // Display packet information 
     InetAddress remote_addr = packet.getAddress(); 
     outputArea.append("Sender: " + remote_addr.getHostAddress() + "\n"); 
     outputArea.append("From Port: " + packet.getPort() + "\n"); 

     CLIENT_HOSTNAME = remote_addr.getHostAddress(); 
     //CLIENT_PORT_NUMBER = Integer.toString(packet.getPort()); 

     // Display packet contents, by reading from byte array 
     ByteArrayInputStream bin = new ByteArrayInputStream(packet.getData()); 

     // Display only up to the length of the original UDP packet 
     for(int i = 0; i < packet.getLength(); i++){ 
      int data = bin.read(); 
      if(data == -1){ 
       break; 
      } 
      else{ 
       message = message + (char)data; 
       //outputArea.append(Character.toString((char)data)); 
      } 
     } 
     socket.close(); 
     return message; 
    } 
    catch(IOException e){ 
     outputArea.append("Error: " + e + "\n"); 
     message = "Error: " + e; 
     return message; 
    } 
} 

여러분이 제공 할 수있는 도움이 있으면 대단히 감사하겠습니다. 내가 알아 내려고하는 주요한 점은 서버와 클라이언트가 메시지를주고받을 수있는 방법입니다. 선배 들께 감사드립니다.

편집 : 나는이 프로젝트를 실행할 때

가 나는 또한 넷빈즈 지금 오류를 얻고있다. 나는 그것이 UDPReceiver 방법에 코드 줄 함께 할 수있는 뭔가가 생각 :

socket = new DatagramSocket(Integer.parseInt(portNum)); 

을하지만 그 잘못이 무엇인지 알아낼 수 없습니다. 그것이 당신이 접근

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: null 
at java.lang.Integer.parseInt(Integer.java:454) 
at java.lang.Integer.parseInt(Integer.java:527) 
at tftp_gui.main.UDPReceiver(main.java:508) 
at tftp_gui.main.access$800(main.java:20) 
at tftp_gui.main$10.run(main.java:374) 
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) 
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721) 
at java.awt.EventQueue.access$200(EventQueue.java:103) 
at java.awt.EventQueue$3.run(EventQueue.java:682) 
at java.awt.EventQueue$3.run(EventQueue.java:680) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 
at java.awt.EventQueue.dispatchEvent(EventQueue.java:691) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244) 
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139) 
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97) 

답변

0

는 파일을 찾을 수없는 경우에 당신이 결과를 다시 보내지 않고 있기 때문에 어쨌든 특정 문제가, 오픈 클라이언트 포트 잘못 필요합니다 :

검사 :

if(check == true){ 
    outputArea.append("File location verified..." + "\n"); 
    outputArea.append("Initiating transfer...." + "\n\n"); 
    UDPSender(CLIENT_HOSTNAME, CLIENT_PORT_NUMBER, "1"); 
} 
else { 
    outputArea.append("File does not exist..." + "\n"); 
    outputArea.append("Exiting run..." + "\n"); 
    UDPSender(CLIENT_HOSTNAME, CLIENT_PORT_NUMBER, "0"); // here you should send 0 
} 
또한

, 여기에 작은 문제를 가지고있다 - 당신이있어 십이하지 않은 if(message == "1")if ("1".equals(message))

귀하의 오류처럼 보일 것 자체 설명 할 것입니다 적절한 CLIENT_PORT_NUMBER 또는 SERVER_PORT_NUMBER lared, 여기에 내가 테스트를 위해 사용했던 것입니다 :

private final static String SERVER_PORT_NUMBER = "1234"; 
private static String CLIENT_HOSTNAME; 
private static final String CLIENT_PORT_NUMBER = "2345"; 
private static final String FILE_REQUEST = "a.txt"; 
private static final String SHARED_DIR = "d:/"; 
private static final String SERVER_HOSTNAME = "localhost"; 
+0

나는 그것을 이해합니다. 나는 그 부분을 거기에 넣는 것을 잊어 버렸다. 이것을 테스트하기 위해 사용하고있는 파일이 실제로 있습니다. 그러나 나는 그 코드를 프로그램에 넣었지만 아직 응답을받지 못했습니다. – jwebster

+0

@jwebster 코드를 테스트했지만 작은 오류가 발견되었지만 전체 수신 - 수신 부분이 정상적으로 작동 함 –

관련 문제