2017-01-21 5 views
0

サーバーがクライアントにファイルを送信し、クライアントがそのファイルを宛先フォルダに保存するサンプルクライアント - サーバーソケットプロジェクトを実行しています。それはうまく動作しますが、ONCEのみ動作します。別のファイルを送信するには、サーバーを再起動してクライアントを再接続する必要があります。Javaクライアント - サーバーソケットは1つのファイルしか送信できません

私は間違っていますか?

サーバー:私は、サーバーからファイルを送信するために使用

public void doConnect() { 
     try { 
      InetAddress addr = InetAddress.getByName(currentIPaddress); 
      serverSocket = new ServerSocket(4445, 50, addr); 

      isServerStarted = true; 

      socket = serverSocket.accept(); 

      inputStream = new ObjectInputStream(socket.getInputStream()); 
      outputStream = new ObjectOutputStream(socket.getOutputStream()); 
      String command = inputStream.readUTF(); 
      this.statusBox.setText("Received message from Client: " + command); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

方法

public void sendFile() { 
     fileEvent = new FileEvent(); 
     String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1, sourceFilePath.length()); 
     String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1); 
     fileEvent.setDestinationDirectory(destinationPath); 
     fileEvent.setFilename(fileName); 
     fileEvent.setSourceDirectory(sourceFilePath); 
     File file = new File(sourceFilePath); 
     if (file.isFile()) { 
      try { 
       DataInputStream diStream = new DataInputStream(new FileInputStream(file)); 
       long len = (int) file.length(); 
       byte[] fileBytes = new byte[(int) len]; 
       int read = 0; 
       int numRead = 0; 
       while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read, fileBytes.length - read)) >= 0) { 
        read = read + numRead; 
       } 
       fileEvent.setFileSize(len); 
       fileEvent.setFileData(fileBytes); 
       fileEvent.setStatus("Success"); 
      } catch (Exception e) { 
       e.printStackTrace(); 
       fileEvent.setStatus("Error"); 
      } 
     } else { 
      System.out.println("path specified is not pointing to a file"); 
      fileEvent.setStatus("Error"); 
     } 
     //Now writing the FileEvent object to socket 
     try { 
      outputStream.writeUTF("newfile"); 
      outputStream.flush(); 

      outputStream.writeObject(fileEvent); 

      String result = inputStream.readUTF(); 
      System.out.println("client says: " + result); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

クライアント

コードが何のために使用さ
public void connect() { 
     int retryCount = 0; 

     while (!isConnected) { 
      if (retryCount < 5) { 
       try { 
        socket = new Socket(currentIPAddress, currentPort); 

        outputStream = new ObjectOutputStream(socket.getOutputStream()); 
        inputStream = new ObjectInputStream(socket.getInputStream()); 
        isConnected = true; 

        //connection success 
        String command = inputStream.readUTF(); 

        if (command.equals("newfile")) { 
         this.clientCmdStatus.setText("Received a file from Server"); 
         outputStream.writeUTF("Thanks Server! Client Received the file"); 
         outputStream.flush(); 
         try { 
          Thread.sleep(1000); 
         } catch (InterruptedException ex) { 
          ex.printStackTrace(); 
         } 
         new Thread(new DownloadingThread()).start(); 
        } 

       } catch (IOException e) { 
        e.printStackTrace(); 
        retryCount++; 
       } 
      } else { 
       //Timed out. Make sure Server is running & Retry 
       retryCount = 0; 
       break; 
      } 
     } 
    } 

サーバが別の受け入れ(およびそれ以上)を得るためには、クライアントにファイル

public void downloadFile() { 
     try { 
      fileEvent = (FileEvent) inputStream.readObject(); 
      if (fileEvent.getStatus().equalsIgnoreCase("Error")) { 
       System.out.println("Error occurred ..So exiting"); 
       System.exit(0); 
      } 

      String outputFile = destinationPath + fileEvent.getFilename(); 

      if (!new File(destinationPath).exists()) { 
       new File(destinationPath).mkdirs(); 
      } 

      dstFile = new File(outputFile); 
      fileOutputStream = new FileOutputStream(dstFile); 
      fileOutputStream.write(fileEvent.getFileData()); 
      fileOutputStream.flush(); 
      fileOutputStream.close(); 
      System.out.println("Output file : " + outputFile + " is successfully saved "); 
      serverResponsesBox.setText("File received from server: " + fileEvent.getFilename()); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
+1

"...それは一度しか動作しません"。二度お試しになるとどうなりますか? 2回試行するコードはどこにありますか?どのようなエラーが観察されますか? –

+0

サーバーは正常にファイルを送信します。だからそれは言う..そしてクライアントは応答を示さない。 2番目のファイルは保存されず、エラーは発生しません@JamesKPolk – Dinuka

答えて

0

接続をwnloading、あなたはループ

while(someConditionIndicatingYourServerShouldRun) { 
    Socker socket = serverSocket.accept(); 
    //respond to the client 

} 

にそれを置くために持っている私は、スレッドプールを使用することをお勧めしたいと処理をスレッドプールに提出します。つまり、ExecutorServiceを使用します。さらに、終了したらストリームなどのリソースを閉じる必要があります。「リソースを試してみる」構造が役立ちます。あなたのコードはこのように見えるかもしれません。

ServerSocket serverSocket = ...; 
ExecutorService threadPool = Executors.newFixedThreadPool(10); 
AtomicBoolean running = new AtomicBoolean(true); 
while(running.get()) { 
    Socket socket = serverSocket.accept(); 
    threadPool.submit(() -> { 
    try(ObjectInputStream is = new ObjectInputStream(socket.getInputStream()); 
     OutputStream os = new ObjectOutputStream(socket.getOutputStream())) { 
     String command = is.readUTF(); 
     if("shutdown".equals(command)) { 
      running.set(false); 
     } else { 
      this.statusBox.setText("Received message from Client: " + command);  
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    }); 
} 
関連する問題