简体   繁体   English

Java中的流管理-客户端/服务器发送和接收文件

[英]Stream management in java - Client/Server sending and recieving files

I have trouble with my streams. 我的信息流有问题。 I'm using multi-threaded client and server so that i could upload or download files one after another, but after getting the first file ( doesn't matter if I send a file to the server or recieve a file from it ), I can not continue with my second file. 我正在使用多线程客户端和服务器,以便可以一个接一个地上传或下载文件,但是在获取第一个文件之后(无论我将文件发送到服务器还是从中接收文件都没有关系),我无法继续我的第二个文件。

Stream closes and I can't figure out how to maintain the stream without corrupting my file. 流关闭,我不知道如何在不破坏文件的情况下维护流。 Without 'stream'.close and some other methods. 没有'stream'.close和其他方法。

I know it's not the best idea, probably completely unacceptable, it is just that I'm completelly lost by now. 我知道这不是最好的主意,可能是完全不能接受的,只是到现在我已经完全迷失了。

Where did I screw up? 我在哪里弄糟?

Server part: 服务器部分:

public class ServerCommunicationThread extends Thread
{

   ...

   public ServerCommunicationThread(Socket socket) throws IOException,
         ParserConfigurationException, TransformerException
   {
     ...
   }

   public synchronized void run()
   {
      try
      {
         String clientSelection;
         while ((clientSelection = inFromClient.readLine()) != null)
         {
            switch (clientSelection)
            {
               case "1":
                  receiveFile();
                  break;
               case "2":
                  String outGoingFileName;
                  while ((outGoingFileName = inFromClient.readLine()) != null)
                  {
                     sendFile(outGoingFileName);
                  }
                  break;
               case "3":
               {
                  disconnect();
                  break;
               }
               default:
                  System.out.println("Incorrect command received.");
                  break;
            }
         }
      }
      catch (IOException e)
      {
         // System.out.println(clientSocket + "--->  Action performed");
         e.printStackTrace();
      }
   }

   public synchronized void receiveFile()
   {
      try
      {
         int bytesRead;

         DataInputStream clientData = new DataInputStream(
               clientSocket.getInputStream());

         String fileName = clientData.readUTF();
         OutputStream output = new FileOutputStream((filePath
               + "received_from_client_" + fileName));
         long size = clientData.readLong();
         byte[] buffer = new byte[1024];
         while (size > 0
               && (bytesRead = clientData.read(buffer, 0,
                     (int) Math.min(buffer.length, size))) != -1)
         {
            output.write(buffer, 0, bytesRead);
            size -= bytesRead;
         }

         output.close();
         clientData.close();

         System.out.println("File " + fileName + " received from client.");
      }
      catch (IOException ex)
      {
         System.err.println("Client error. Connection closed.");
      }
   }

   public synchronized void sendFile(String fileName)
   {
      try
      {

         File myFile = new File(fileName);
         byte[] mybytearray = new byte[(int) myFile.length()];

         FileInputStream fileInStream = new FileInputStream(myFile);
         BufferedInputStream bufferedInStream = new BufferedInputStream(
               fileInStream);


         DataInputStream dataInStream = new DataInputStream(bufferedInStream);
         dataInStream.readFully(mybytearray, 0, mybytearray.length);


         OutputStream outStream = clientSocket.getOutputStream();

         DataOutputStream dataOutStream = new DataOutputStream(outStream);
         dataOutStream.writeUTF(myFile.getName());
         dataOutStream.writeLong(mybytearray.length);
         dataOutStream.write(mybytearray, 0, mybytearray.length);
         dataOutStream.flush();
         System.out.println("File " + fileName + " sent to client.");
      }
      catch (Exception e)
      {
         System.err.println("File does not exist!");
      }
   }

}

Client: 客户:

public class ClientConnectAndSender extends Thread
{
  ...

   public ClientConnectAndSender() throws IOException
   {
      ...
   }

   public synchronized void startSending() throws IOException,
         ParserConfigurationException, TransformerException
   {
      while (ServerRunning)
      {
         outStream = new PrintStream(clientSocket.getOutputStream());

         try
         {
            switch (Integer.parseInt(selectAction()))
            {
               case 1:
                  outStream.println("1");
                  sendFile();
                  break;
               case 2:
                  outStream.println("2");
                  System.err.print("Enter file name: ");
                  fileName = inFromServer.readLine();
                  outStream.println(fileName);
                  receiveFile(fileName);
                  break;
               case 3:
                  outStream.println("3");
                  disconnect();
                  break;
            }
         }
         catch (Exception e)
         {
            System.err.println("not valid input");
         }

         recieverThread = new ClientRecieverThread(inFromServer);
         recieverThread.start();
      }
   }

   public String selectAction() throws IOException
   {
      System.out.println("1. Send file.");
      System.out.println("2. Recieve file.");
      System.out.println("3. End session");
      System.out.print("\nMake selection: ");

      return inFromServer.readLine();
   }

   public synchronized void sendFile()
   {
      try
      {
         System.err.print("Enter file name: ");
         fileName = inFromServer.readLine();

         File myFile = new File(fileName);
         byte[] mybytearray = new byte[(int) myFile.length()];

         FileInputStream fileInStream = new FileInputStream(myFile);
         BufferedInputStream bufferedInStream = new BufferedInputStream(
               fileInStream);
         // bis.read(mybytearray, 0, mybytearray.length);

         DataInputStream dataInStream = new DataInputStream(bufferedInStream);
         dataInStream.readFully(mybytearray, 0, mybytearray.length);

         OutputStream outStream = clientSocket.getOutputStream();

         // Sending file name and file size to the server
         DataOutputStream dataOutStream = new DataOutputStream(outStream);
         dataOutStream.writeUTF(myFile.getName());
         dataOutStream.writeLong(mybytearray.length);
         dataOutStream.write(mybytearray, 0, mybytearray.length);
         dataOutStream.flush();
         System.out.println("File " + fileName + " sent to Server.");
      }
      catch (Exception e)
      {
         System.err.println("File does not exist!");
      }
   }

   public synchronized void receiveFile(String fileName)
   {
      try
      {
         int bytesRead;
         InputStream inputStream = clientSocket.getInputStream();

         DataInputStream clientData = new DataInputStream(inputStream);

         fileName = clientData.readUTF();
         OutputStream outputStream = new FileOutputStream((filePath
               + "received_from_server_" + fileName));
         long size = clientData.readLong();
         byte[] buffer = new byte[1024];
         while (size > 0
               && (bytesRead = clientData.read(buffer, 0,
                     (int) Math.min(buffer.length, size))) != -1)
         {
            outputStream.write(buffer, 0, bytesRead);
            size -= bytesRead;
         }

         // outputStream.flush();
         outputStream.close();
         inputStream.close();
         // try
         // {
         // in.available();
         // output.flush();
         // }
         // catch (Exception e)
         // {
         // e.printStackTrace();
         // }

         System.out.println("File " + fileName + " received from Server.");
      }
      catch (IOException ex)
      {

         ex.printStackTrace();
      }
   }

}

The lines clientData.close() on the server and inputStream.close(); 服务器上的clientData.close()行和inputStream.close(); on the client are closing the socket.... 在客户端上正在关闭套接字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM