2013-11-27 1 views
0

한 사용자가 다른 사용자와주고받을 수있는 코드를 작성하려고합니다. sendFile이라는 파일을 보내는 방법을 작성했습니다. 파일을 보냈지 만 보낸 파일이 저장된 위치를 찾을 수 없습니다.Java로 파일 전송 사용자 :

서버 측 :

package DFT; 

import java.io.BufferedInputStream; 
import java.io.BufferedReader; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.PrintStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.PrintWriter; 
import java.net.Socket; 
import java.net.ServerSocket; 

public class ServerSide { 
    private static ServerSocket serverSocket = null; 
    private static Socket clientSocket = null; 
    private static final int maxClientsCount = 10; 
    private static final clientThread[] threads = new clientThread[maxClientsCount]; 

    public static void main(String args[]) { 

     try { 
      serverSocket = new ServerSocket(2222); 
      System.out.println("Distributed File Transfer Server has successfully started"); 
     } catch (IOException e) { 
      System.out.println(e); 
     } 

     while (true) { 
      try { 
       clientSocket = serverSocket.accept(); 
       int i; 
       for (i = 0; i < maxClientsCount; i++) { 
        if (threads[i] == null) { 
         (threads[i] = new clientThread(clientSocket, threads)).start(); 
         break; 
        } 
       } 
       if (i == maxClientsCount) { 
        PrintStream os = new PrintStream(clientSocket.getOutputStream()); 
        os.println("Server too busy. Try later."); 
        os.close(); 
        clientSocket.close(); 
       } 
      } catch (IOException e) { 
       System.err.println(e); 
      } 
     } 
    } 
} 

class clientThread extends Thread { 
    // private DataInputStream is = null; 
    private PrintStream os = null; 
    private BufferedReader is; 
    // private PrintWriter os; 
    private Socket clientSocket = null; 
    private final clientThread[] threads; 
    private int maxClientsCount; 
    private String name, pass; 
    private int id; 
    private static final int totalUser = 5; 
    private static final String username[] = new String[totalUser]; 
    private static final String password[] = new String[totalUser]; 
    private static boolean online[] = new boolean[totalUser]; 

    public clientThread(Socket clientSocket, clientThread[] threads) { 
     this.clientSocket = clientSocket; 
     this.threads = threads; 

     username[0] = "user1"; 
     username[1] = "user2"; 
     username[2] = "user3"; 
     username[3] = "user4"; 
     username[4] = "user5"; 
     password[0] = "123"; 
     password[1] = "456"; 
     password[2] = "789"; 
     password[3] = "012"; 
     password[4] = "345"; 

     maxClientsCount = threads.length; 
    } 

    @Override 
    public void run() { 
     int maxClientsCount = this.maxClientsCount; 
     clientThread[] threads = this.threads; 

     try { 
      /* 
      * Create input and output streams for this client. 
      */ 
      is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
      os = new PrintStream(clientSocket.getOutputStream()); 

      if (is.readLine().trim().equals("login")) { 
       name = is.readLine().trim(); 
       pass = is.readLine().trim(); 
      } 

      int i, j; 

      for (i = 0; i < totalUser; i++) { 
       if (name.equals(username[i]) && pass.equals(password[i])) { 
        break; 
       } 
      } 

      if (i < totalUser) { 

       if (online[i]) { 
        os.println("This user already logged in"); 
        threads[i] = null; 
        is.close(); 
        os.close(); 
        clientSocket.close(); 
        return; 
       } else { 
        for (j = 0; j < maxClientsCount; j++) { 
         if (threads[j] == this) { 
          threads[j].id = i; 
          online[i] = true; 
         } 
         if (threads[j] != null) { 
          threads[j].os.println("<Server Message>: A new user " + name + " has logged in"); 
         } 
        } 
       } 

      } else { 
       os.println("Invalid Username & Password. Terminating"); 
       for (i = 0; i < maxClientsCount; i++) { 
        if (threads[i] == this) { 

         threads[i] = null; 
         is.close(); 
         os.close(); 
         clientSocket.close(); 
         return; 
        } 
       } 
      } 

      while (true) { 
       String line = is.readLine(); 
       System.out.println("#### " + line); 

       if (line.startsWith("logout")) { 
        os.println("Successfully logged out"); 

        online[id] = false; 

        for (i = 0; i < maxClientsCount; i++) { 
         if (threads[i] != null) { 
          if (threads[i] == this) 
           threads[i] = null; 
          else 
           threads[i].os.println("<Server message>: " + name + " has logged out"); 
         } 
        } 

        is.close(); 
        os.close(); 
        clientSocket.close(); 
        return; 
       } 

       if (line.startsWith("sendfile ")) { 
        String subline = line.substring(15); 
        String temp = line.substring(9, 14); 
        for (i = 0; i < totalUser; i++) { 
         if (username[i].equals(temp)) { 
          break; 
         } 
        } 

        if (i == totalUser) { 
         os.println("Invalid username"); 
         continue; 
        } 

        int k = i; 

        if (!online[k]) { 
         os.println("<Failure>: " + temp + " is not online"); 
        } else { 
         os.println("file sent"); 

         for (j = 0; j < maxClientsCount; j++) { 
          if (threads[j] != null && threads[j].id == k) { 
           threads[j].os.println("<" + name + "> " + subline); 
          } 
         } 
         sendFile(subline); 
         break; 
        } 
       } 

       if (line.startsWith("send ")) { 
        String subline = line.substring(11); 
        String temp = line.substring(5, 10); 

        for (i = 0; i < totalUser; i++) { 
         if (username[i].equals(temp)) { 
          break; 
         } 
        } 

        if (i == totalUser) { 
         os.println("Invalid username"); 
         continue; 
        } 

        int k = i; 

        if (!online[k]) { 
         os.println("<Failure>: " + temp + " is not online"); 
        } 

        else { 
         os.println("message sent"); 

         for (j = 0; j < maxClientsCount; j++) { 
          if (threads[j] != null && threads[j].id == k) { 
           threads[j].os.println("<" + name + ">: " + subline); 
          } 
         } 
        } 
       } 
      } 
     } catch (IOException e) { 
      System.err.println(e); 
     } 
    } 

    public void receiveFile() { 
     try { 
      int bytesRead; 
      DataInputStream clientData = null; 
      try { 
       DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream()); 
       clientData = dataInputStream; 
      } catch (IOException e) { 
       System.err.println(e); 
      } 
      String fileName = clientData.readUTF(); 
      OutputStream output = new FileOutputStream(("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 e) { 
      System.err.println(e); 
      System.err.println("Client error. Connection closed."); 
     } 
    } 

    public void sendFile(String fileName) { 
     try { 
      File file = new File(fileName); 
      byte[] bytearray = new byte[(int) file.length()]; 
      FileInputStream fis = new FileInputStream(file); 
      BufferedInputStream bis = new BufferedInputStream(fis); 
      DataInputStream dis = new DataInputStream(bis); 
      dis.readFully(bytearray, 0, bytearray.length); 
      OutputStream os = clientSocket.getOutputStream(); 
      DataOutputStream dos = new DataOutputStream(os); 
      dos.writeUTF(file.getName()); 
      dos.writeLong(bytearray.length); 
      dos.write(bytearray, 0, bytearray.length); 
      dos.flush(); 
      System.out.println("File " + fileName + " sent to client."); 
     } catch (IOException e) { 
      System.err.println("File does not exist!"); 
      System.err.println(e); 
     } 
    } 
} 

클라이언트 측 :

package DFT; 

import java.io.BufferedInputStream; 
import java.io.DataInputStream; 
import java.io.PrintStream; 
import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.InputStreamReader; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.io.PrintWriter; 
import java.net.Socket; 
import java.net.UnknownHostException; 

public class ClientSide implements Runnable { 
    private static Socket clientSocket = null; 
    private static PrintStream os = null; 
    // private static PrintWriter os; 
    // private static DataInputStream is = null; 
    private static BufferedReader inputLine, is; 
    private static boolean closed = false; 
    private static String username, password; 

    public static void main(String[] args) { 

     try { 
      clientSocket = new Socket("localhost", 2222); 
      inputLine = new BufferedReader(new InputStreamReader(System.in)); 
      os = new PrintStream(clientSocket.getOutputStream()); 
      is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     } catch (UnknownHostException unknownHostException) { 
      System.err.println("Don't know about host"); 
      System.err.print(unknownHostException); 
     } catch (IOException e) { 
      System.err.println("Couldn't get I/O for the connection to the host"); 
      System.err.println(e); 
     } 

     if (clientSocket != null && os != null && is != null) { 
      try { 

       // Creates a thread to read from the server. 
       new Thread(new ClientSide()).start(); 

       System.out.println("Enter UserName:"); 
       username = inputLine.readLine().trim(); 
       System.out.println("Enter Password:"); 
       password = inputLine.readLine().trim(); 

       os.println("login"); 
       os.println(username); 
       os.println(password); 

       while (!closed) { 
        os.println(inputLine.readLine().trim()); 
       } 

       os.close(); 
       is.close(); 
       clientSocket.close(); 
      } catch (IOException e) { 
       System.err.println("IOException: " + e); 
      } 
     } 
    } 

    @Override 
    public void run() { 

     String responseLine; 
     try { 
      while ((responseLine = is.readLine()) != null) { 
       System.out.println(responseLine); 
       if (responseLine.indexOf("*** Bye") != -1) { 
        break; 
       } 
      } 
      closed = true; 
     } catch (IOException e) { 
      System.err.println("IOException: " + e); 
     } 
    } 

    public void receiveFile() { 
     try { 
      int bytesRead; 
      DataInputStream clientData = null; 
      try { 
       DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream()); 
       clientData = dataInputStream; 
      } catch (IOException e) { 
       System.err.println(e); 
      } 
      String fileName = clientData.readUTF(); 
      OutputStream output = new FileOutputStream(("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 e) { 
      System.err.println(e); 
      System.err.println("Client error. Connection closed."); 
     } 
    } 

    public void sendFile(String fileName) { 
     try { 
      File file = new File(fileName); 
      byte[] bytearray = new byte[(int) file.length()]; 
      FileInputStream fis = new FileInputStream(file); 
      BufferedInputStream bis = new BufferedInputStream(fis); 
      DataInputStream dis = new DataInputStream(bis); 
      dis.readFully(bytearray, 0, bytearray.length); 
      OutputStream os = clientSocket.getOutputStream(); 
      DataOutputStream dos = new DataOutputStream(os); 
      dos.writeUTF(file.getName()); 
      dos.writeLong(bytearray.length); 
      dos.write(bytearray, 0, bytearray.length); 
      dos.flush(); 
      System.out.println("File " + fileName + " sent to client."); 
     } catch (IOException e) { 
      System.err.println("File does not exist!"); 
      System.err.println(e); 
     } 
    } 
} 
+0

코드에 더 많은 메서드를 사용해야합니다. 캐치 예외 등으로 인해 코드가 무엇을하는지 보는 것은 어렵습니다. Apache IO Commons의 IOUtils는 스트림을 닫는 등의 작업을 처리하는 친구입니다. 일부 기능을 테스트하는 것이면 모든 메소드를 throw합니다. 예외를 코드를 조금 정리합니다. –

답변

0

그것은 당신의 receiveFile() 방법은 파일을 만드는 것처럼 보이지만,이 코드에서 호출되지 않습니다.

+0

사용자가 서버에 파일을 보내도록 코드를 작성한 경우 receiveFile()이 파일을 전송할 필요가 없습니다. –

+0

이 대답은 주석이어야합니다. –