2011-01-16 10 views
-4

私はクライアントとサーバーとして働いている2つのクラスをコーディングしています。両方向にファイルを送信できます。いくつかのバグがあります。クライアントからサーバーにファイルをアップロードするとき、ファイルは正常にアップロードできますが、サーバプロセスはInputStreamからのヌルポインタ例外によって停止します。pis = connectionSocket.getInputStream(); 2回目のバグは、ダウンロードが正常に完了し、別のダウンロードをテストしたい場合です。ファイルを正しく送信しませんが、3回目にダウンロードするとうまく動作します。次のコードは、あなたがc:\ users \ file.fileのようなものを入力しなければならないファイル名を入力するように頼んだときに得たものです。誰かがそれで私を助けることを願っています、ありがとうございます。 tcpserver.javajava 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

入力ストリーム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:2番目のセクションでcatchブロックの後に*例外が発生しています。それはtryブロックの内側にもなければなりません。 – EJP

1

私はこの問題は、あなたのことである疑いがありますconnectionSocket.getInputStreamを2回呼び出しています。ストリームは一度しか取得せず、接続プロセスの存続期間中に使用する必要があります。

これは無関係ですが、なぜクライアントクラスに3つのScannerインスタンスがあるのですか?あなたは1つだけ必要です。彼らはすべて、同じ基礎ストリーム(System.in)から読んでいます。

+0

connectionSocket.getInputStreamを呼び出す変更を行った後、まだ正常に動作していない、ヌルポインタの例外はありませんが、以前に発生しなかった最初の要求の後にサーバーが他の要求に応答していません。 – starcaller

+0

@ Starcaller:デバッガでコードをステップ実行するか、System.out.println文をたくさん追加して、何が起こっているのかを正確に確認することをお勧めします。デバッグコードは簡単ではなく、実践的です。 –

+0

正直言って、これらのバグがポップアップした最初の瞬間に私はこれを行いました。私は助けを求めています。System.out.printlnをたくさん印刷した後に何が起こっているのか分かりません。 – starcaller

関連する問題