2011-01-16 2 views
-4

클라이언트와 서버로 작동하는 두 개의 클래스를 코딩했습니다. 두 가지 방향으로 파일을 전송할 수 있습니다. 몇 가지 버그가 있습니다. 클라이언트에서 서버로 파일을 업로드 할 때 가장 먼저 버그가 발생합니다. 파일을 성공적으로 업로드 할 수 있지만 서버 프로세스는 InputStream의 null 포인터 예외로 중지됩니다. pis = connectionSocket.getInputStream(); 두 번째 버그는 성공적으로 다운로드하고 다른 다운로드를 테스트하려는 경우 파일을 제대로 전송하지 않지만 세 번째로 다운로드하면 잘 작동합니다. 다음 코드는 c : \ users \ file.file과 같이 입력해야하는 파일 이름을 입력하라는 메시지가 표시 될 때 내가 가지고있는 코드입니다. 누군가가 나를 도와 줄 수 있기를 바랍니다. 감사합니다. tcpserver.java자바 tcp 버그를 수정해야합니다

import java.io.*; 
import java.net.*; 

class TCPServer { 

public static void main(String args[]) { 
    String direction=""; 
    String filename=""; 
    byte[] aByte = new byte[1]; 
    int bytesRead; 

    while (true) { 
     ServerSocket welcomeSocket = null; 
     Socket connectionSocket = null; 
     BufferedOutputStream outToClient = null; 
     BufferedReader inFromClient =null; 

     try { 
      welcomeSocket = new ServerSocket(3248); 
      connectionSocket = welcomeSocket.accept(); 
      outToClient = new BufferedOutputStream(connectionSocket.getOutputStream()); 
      System.out.println("connection is established with    "+connectionSocket.getInetAddress()+"using port "+connectionSocket.getPort()); 
      inFromClient =new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream())); 

      direction = inFromClient.readLine(); 
      System.out.println("client wants to "+direction); 
      filename=inFromClient.readLine(); 
      System.out.println("file directory and name is "+filename); 



     } catch (IOException ex) { 
      // Do exception handling 
     } 

     if (outToClient != null&&direction.equals("download")) { 
      File myFile = new File(filename); 
      byte[] mybytearray = new byte[(int) myFile.length()]; 

      FileInputStream fis = null; 

      try { 
       fis = new FileInputStream(myFile); 
      } catch (FileNotFoundException ex) { 
       System.out.println("can't find file"); 
       // Do exception handling 
      } 
      BufferedInputStream bis = new BufferedInputStream(fis); 

      try { 
       bis.read(mybytearray, 0, mybytearray.length); 
       outToClient.write(mybytearray, 0, mybytearray.length); 
       outToClient.flush(); 
       outToClient.close(); 
       connectionSocket.close(); 
       fis.close(); 
       bis.close(); 
       inFromClient.close(); 


      } catch (IOException ex) { 
       // Do exception handling 
      } 
     } 
     if(direction.equals("upload")) 
     { 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
      //byte[] yourByteArray = new byte[10240]; 
      File serverFile = new File(filename); 
      FileOutputStream fos = null; 
     BufferedOutputStream bos = null; 

     try { 
      InputStream pis = connectionSocket.getInputStream(); 
      fos = new FileOutputStream(filename); 
      bos = new BufferedOutputStream(fos); 
      bytesRead = pis.read(aByte, 0, aByte.length); 

      do { 
        baos.write(aByte); 
        bytesRead = pis.read(aByte); 
      } while (bytesRead != -1&&aByte!=null); 

      bos.write(baos.toByteArray()); 
      bos.flush(); 
      bos.close(); 
      //clientSocket.close(); 
     } catch (IOException ex) { 
      // Do exception handling 
     } 

     System.out.println("The file transmission finishes!"); 

    } 
} 
} 

}

TCPClient.java는

import java.io.*; 

    import java.io.ByteArrayOutputStream; 
    import java.net.*; 
    import java.util.*; 

class TCPClient { 

public static void main(String args[]) { 
    byte[] aByte = new byte[1]; 
    int bytesRead; 
    String downloadfile; 
    String downloadfilere; 
    String uploadfile; 
    String uploadfilese; 
    Socket clientSocket = null; 
    InputStream is = null; 
    String ip; 
    int port; 
    String conti; 

    boolean goon=true; 
    int situation; 
    Scanner sc=new Scanner(System.in); 
    Scanner sc1=new Scanner(System.in); 
    Scanner sc2=new Scanner(System.in); 
    System.out.println("please input the ip address for the host"); 
    ip=sc.nextLine(); 
    System.out.println("please input the port number"); 
    port=sc.nextInt(); 
    DataOutputStream outToServer=null; 
    BufferedOutputStream fileoutToServer = null; 



    while(goon=true){ 
    try { 
     clientSocket = new Socket(ip, port); 
     is = clientSocket.getInputStream(); 
     System.out.println("connection is established"); 
     outToServer = new DataOutputStream(clientSocket 
.getOutputStream()); 
    } catch (IOException ex) { 
     // Do exception handling 
    } 

    System.out.println("what request do you want to make: "+"\n"+"1.download"+"\n"+"2.upload"); 
    situation=sc.nextInt(); 
    if(situation==1){ 
     try{ outToServer.writeBytes("download"+ "\n"); 
     outToServer.flush();}catch(IOException ex){} 
     System.out.println("please enter the file name for download"); 
     downloadfile=sc1.nextLine(); 
     //try{ outToServer.writeBytes("download"+ "\n");}catch(IOException ex){} 
     System.out.println("please enter the file name you want the received file to be saved as"); 
     downloadfilere=sc2.nextLine(); 
     try{ outToServer.writeBytes(downloadfile+ "\n"); 
     outToServer.flush(); 
     }catch(IOException ex){} 

    if(downloadfile!=""){ 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

    if (is != null) { 

     FileOutputStream fos = null; 
     BufferedOutputStream bos = null; 
     try { 
      fos = new FileOutputStream(downloadfilere); 
      bos = new BufferedOutputStream(fos); 
      bytesRead = is.read(aByte, 0, aByte.length); 

      do { 
        baos.write(aByte); 
        bytesRead = is.read(aByte); 
      } while (bytesRead != -1); 

      bos.write(baos.toByteArray()); 
      bos.flush(); 
      bos.close(); 
      clientSocket.close(); 
     } catch (IOException ex) { 
      // Do exception handling 
     } 
    }} 
    System.out.println("file received successfully"); 
    } 
    if(situation==2) 
    { 
     try{ outToServer.writeBytes("upload"+ "\n");}catch(IOException ex){} 
     System.out.println("please enter the file name for upload"); 
     uploadfile=sc1.nextLine(); 
     System.out.println("please enter the file name on server for upload"); 
     uploadfilese=sc2.nextLine(); 
     try{ outToServer.writeBytes(uploadfilese+ "\n");}catch(IOException ex){} 

     File myFile = new File(uploadfile); 
     byte[] yourByteArray = new byte[1024];//* 
     try{ 
      FileInputStream pfis = new FileInputStream(myFile); 
     //BufferedInputStream bbis=new BufferedInputStream(pfis); 
     int pnread=0; 
     OutputStream pbos = clientSocket.getOutputStream(); 
         //System.out.println("pfis.read(yourByteArray)"+pfis.read(yourByteArray));//*** 
      while((pnread=pfis.read(yourByteArray))>0) 
     { 
     pbos.write(yourByteArray, 0, pnread); 
     //System.out.println("pfis.read(yourByteArray)"+pnread);//*** 
      pbos.flush(); 
      } 
      pbos.close(); 
     }catch(IOException ex){} 


    } 

    System.out.println("do you want to do another request?"); 
    conti=sc.nextLine(); 
    if(conti.equals("yes")) 
     goon=true; 
    else 
     goon=false; 
    //try{clientSocket.close();}catch(IOException ex){} 
} 
} 

}

오류 메시지가 :

Exception in thread "main" java.lang.NullPointerException 
    at TCPServer.main(TCPServer.java:79) 
    Java Result: 1 
+0

주석 처리 된 내용과 관련이없는 내용을 모두 제거하여 "코드 벽"을 줄일 수 있습니까? 또한 예외에 대한 스택 추적을 포함하고 사람들이 문제의 위치를 ​​정확하게 볼 수 있도록 줄을 표시하십시오. –

+0

@Cameron : 불편을 끼쳐 드려 죄송합니다. 코드를 업데이트했습니다. – starcaller

+0

라인 79는 어느 것입니까? –

답변

3

의 InputStream PIS = connectionSocket.getInputStream에서 널 포인터 예외()

그래서 'connectionSocket'널. 이는 잘못된 실행 처리 구조로 인해 발생합니다. 'connectionSocket'을 생성하지 못하고 catch 블록 뒤의 코드를 계속 수행하지 않으면 어떻게되는지 생각해보십시오. 'connectionSocket'을 사용하는 모든 코드는 그것을 구성하는 'try'블록 안에 있어야합니다.

또한 read() 메서드의 결과를 무시하고 가능한 최대 데이터 양을 반환했다고 가정합니다. 이를 명시하지 않았습니다.

int count; 
while ((count = in.read(buffer)) > 0) 
    out.write(buffer, 0, count); 
+0

답장을 보내 주셔서 감사합니다. 하지만 connectionSocket을 사용하는 구문은 이미 try 블록에 모두 들어 있으므로 예외가 계속 발생하는 이유가 혼란 스럽습니다. – starcaller

+0

@starcaller : 두 번째 섹션에서 * catch 블록 뒤의 예외가 발생합니다. 그것은 try 블록 안에 있어야합니다. – EJP

1

나는 생각에 문제가있는 것입니다 connectionSocket.getInputStream을 두 번 호출합니다. 스트림을 한 번만 가져 와서 연결 프로세스의 수명 동안 사용해야합니다.

이것은 관련이 없지만 클라이언트 클래스에 세 개의 Scanner 인스턴스가있는 이유는 무엇입니까? 당신은 오직 하나만 필요합니다. 그들은 모두 같은 기본 스트림 (System.in)에서 독서입니다.

+0

한 번 connectionSocket.getInputStream을 호출하기 위해 변경 한 후에도 여전히 제대로 작동하지 않습니다. 더 이상 null 포인터 예외는 없지만 이전에 발생하지 않은 첫 번째 요청 이후 서버가 다른 요청에 응답하지 않습니다. 감사합니다. – starcaller

+0

@Starcaller : 디버거를 사용하여 코드를 단계별로 실행하거나 많은 'System.out.println' 문을 추가하여 정확히 어떤 일이 일어나는지 확인할 수 있습니다. 디버깅 코드는 쉽지 않으며 실천이 필요합니다. –

+0

솔직히 말해서 나는이 버그가 처음으로 터져서 도움을 요청하고 있습니다. 나는 System.out.println을 많이 인쇄 한 후에 무슨 일이 일어나는지 알 수 없습니다. – starcaller

관련 문제