2014-12-03 213 views
0

我想通過套接字通信從我的服務器發送數據到我的客戶端,並且在接收端收到錯誤。客戶端 - 服務器通信

這裏是我的代碼snippets-

服務器 - 這個類被稱爲CLIENTConnection並負責所有的連接從服務器到客戶端

import java.net.*; 
    import java.util.logging.Level; 
    import java.util.logging.Logger; 
    import java.io.*; 
    public class CLIENTConnection implements Runnable { 

private Socket clientSocket; 
private BufferedReader in = null; 

public CLIENTConnection(Socket client) { 
    this.clientSocket = client; 
} 

@Override 
public void run() { 
    try { 
     in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     String clientSelection=in.readLine(); 
     while (clientSelection != null) { 
      switch (clientSelection) { 
       case "1": 
        receiveFile(); 
        break; 
       case "2": 

        System.out.println("inside case 2"); 
        String outGoingFileName = in.readLine(); 
        System.out.println(outGoingFileName); 

         while (outGoingFileName != null) { 
          System.out.println("Inside while loop"); 
         sendFile(outGoingFileName); 
        } 
        System.out.println("Out of while"); 

        break; 

       case "3": 
        receiveFile(); 
        break; 

       default: 
        System.out.println("Incorrect command received."); 
        break; 
      } 
      in.close(); 
      break; 
     } 

    } catch (IOException ex) { 
     Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 

public void receiveFile() { 
    try { 

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

     String filename = clientData.readUTF(); 
     System.out.println(filename+" is received on server side"); 
     OutputStream output = new FileOutputStream(("C://Users/Personal/workspace/ClientServer/src/dir/"+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 void sendFile(String fileName) { 
try { 
    //handle file read 
    File myFile = new File("C://Users/Personal/workspace/ClientServer/src/dir/"+fileName); 
    byte[] mybytearray = new byte[(int) myFile.length()]; 

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

    DataInputStream dis = new DataInputStream(bis); 
    dis.readFully(mybytearray, 0, mybytearray.length); 

    //handle file send over socket 
    OutputStream os = clientSocket.getOutputStream(); 

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

客戶端(接收文件)

public class FileClient { 



    private static Socket sock; 
    private static String fileName; 
    private static BufferedReader stdin; 
    private static PrintStream os; 

    public static void main(String[] args) throws IOException, ClassNotFoundException { 
     ObjectInputStream inFromServer; 



     try 
     { 
      sock = new Socket("localhost", 7777); 
      stdin = new BufferedReader(new InputStreamReader(System.in)); 
     } catch (Exception e) { 
      System.err.println("Cannot connect to the server, try again later."); 
      System.exit(1); 
     } 


     inFromServer= new ObjectInputStream(sock.getInputStream()); 
     os = new PrintStream(sock.getOutputStream()); 


     try { 
       switch (Integer.parseInt(selectAction())) { 
      case 1: 
       os.println("1"); 
       sendFile(); 
       break; 
      case 2: 
       os.println("2"); 
       System.err.print("Enter file name: "); 
       fileName = stdin.readLine(); 
       os.println(fileName); 
       receiveFile(fileName); 
       break; 

      case 3: 
       os.println("3"); 
       Synchronise(); 

     } 
     } catch (Exception e) { 
      System.err.println("not valid input"); 
     } 


     sock.close(); 


    } 


    private static void Synchronise() 
    { 
     HashMap<String, Calendar> ClientFileList=getTimeStamp("C://Users/Personal/workspace/ClientServer/Client/");//getting the filename and timestamp of all the files present in client folder. 
     /*System.out.println("Client File List : \n"); 
     for(String s : ClientFileList.keySet()) 
      System.out.println(s);*/ 
     HashMap<String, Calendar> ServerFileList=getTimeStamp("C://Users/Personal/workspace/ClientServer/src/dir/");//(HashMap<String, Calendar>) inFromServer.readObject(); 
     /*System.out.println("\nServer File List : \n"); 
     for(String s : ClientFileList.keySet()) 
      System.out.println(s);*/ 
     System.out.println("File comparision output"); 
     compareTimestamp(ClientFileList,ServerFileList); 
    } 




    private static void compareTimestamp(HashMap<String, Calendar> ClientFileList, HashMap<String, Calendar> serverFileList) 
    { 
     LinkedList<String> fileToUpload=new LinkedList<String>(); 
     LinkedList<String> fileToDownload=new LinkedList<String>(); 
     LinkedList<String> fileToDeleteFromClient=new LinkedList<String>(); 
     LinkedList<String> fileToDeleteFromServer=new LinkedList<String>(); 
     Calendar clientCalender = null,serverCalendar=null; 

     for (String filename : serverFileList.keySet()) 
     { 
      serverCalendar=serverFileList.get(filename); 
      if(ClientFileList.containsKey(filename)) 
      { 
       clientCalender=ClientFileList.get(filename); 
       if(clientCalender.before(serverCalendar)) 
       { 
        fileToDownload.add(filename); 
       } 
       else 
       { 
        fileToUpload.add(filename); 
       } 
      } 
      else 
      { 
       fileToDeleteFromClient.add(filename); 
      } 
     } 

     for (String filename : ClientFileList.keySet()) 
     { 
      clientCalender=ClientFileList.get(filename); 
      if(!serverFileList.containsKey(filename)) 
      { 
       fileToDeleteFromServer.add(filename); 
      } 
     } 


     System.out.println("Files to download to client: "+fileToDownload); 
     System.out.println("Files to upload to Server: "+fileToUpload); 
     System.out.println("Files to delete from client: "+fileToDeleteFromClient); 
     System.out.println("Files to delete from Server: "+fileToDeleteFromServer); 

     sendFile(fileToDeleteFromServer); 

    } 


     private static HashMap<String, Calendar> getTimeStamp(String location) 
    { 
     HashMap<String,Calendar> fileList = new HashMap<String,Calendar>(); 
     File dir = new File(location); 

     File[] files = dir.listFiles(); 
     if (files.length == 0) 
     { 
      System.out.println("No file found"); 
      //System.exit(1); 
     } 
     else 
     { 
      for (int i = 0; i < files.length; i++) 
      { 
       Calendar calendar = Calendar.getInstance(); 
       calendar.setTimeInMillis(files[i].lastModified()); 
       fileList.put(files[i].getName(), calendar); 
      } 
     } 
     return fileList; 
    } 



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

     return stdin.readLine(); 
    } 

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

      File myFile = new File("C:/Users/Personal/workspace/ClientServer/Client/"+fileName); 
      byte[] mybytearray = new byte[(int) myFile.length()]; 

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

      DataInputStream dis = new DataInputStream(bis); 
      dis.readFully(mybytearray, 0, mybytearray.length); 

      OutputStream os = sock.getOutputStream(); 

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

    //receive a list of file to upload to server from client. 
    static void sendFile(LinkedList<String> fileList) 
    { 
     for(String file: fileList) 
      sendFile(file); 
    } 

    public static void sendFile(String filename) { 
      File file = new File("C:/Users/Personal/workspace/ClientServer/Client/"+filename); 
      byte[] mybytearray = new byte[(int) file.length()]; 
      FileInputStream fis; 
      try 
      { 
       fis = new FileInputStream(file); 
       BufferedInputStream bis = new BufferedInputStream(fis); 
       //bis.read(mybytearray, 0, mybytearray.length); 

       DataInputStream dis = new DataInputStream(bis); 
       dis.readFully(mybytearray, 0, mybytearray.length); 

       OutputStream os = sock.getOutputStream(); 

       DataOutputStream dos = new DataOutputStream(os); 
       dos.writeUTF(file.getName()); 
       dos.writeLong(mybytearray.length); 
       dos.write(mybytearray, 0, mybytearray.length); 
       dos.flush(); 
       dis.close(); 
       System.out.println("File "+filename+" sent to Server."); 

      } 
      catch (Exception e) 
      { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    public static void receiveFile(String fileName) { 
     try { 
      int bytesRead; 
      InputStream in = sock.getInputStream(); 
      DataInputStream clientData = new DataInputStream(in); 
      fileName = clientData.readUTF(); 
      OutputStream output = new FileOutputStream(("received_from_server_")); 
      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(); 
      in.close(); 

      System.out.println("File "+fileName+" received from Server."); 
     } catch (IOException ex) { 
      Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

}

它向我顯示錯誤在

filename = clientData.readUTF(); 

請讓我知道是否有任何可能的解決方案。

+1

它顯示什麼錯誤?請添加堆棧跟蹤。 – Fildor 2014-12-03 10:57:23

+0

你想給方法參數指定一些東西嗎?你應該使用一個局部變量,如果你以後不需要它或者返回它,而不是在調用者需要的時候使這個方法失效。 – Fildor 2014-12-03 11:00:37

+0

這裏是stacktrace- 2014年12月3日上午6時00分43秒FileClient receiveFile 重度:空 java.io.EOFException的 \t在java.io.DataInputStream.readFully(來源不明) \t在java.io.DataInputStream中.readUTF(來源不明) \t在java.io.DataInputStream.readUTF(來源不明) \t在FileClient.receiveFile(FileClient.java:280) \t在FileClient.main(FileClient.java:53) – 2014-12-03 11:00:58

回答

0

DataInputStream s使用此異常來表示流結束。所以這個例外可能不是一個錯誤,而只是意味着數據已經發送。

在閱讀之前,你必須檢查你確實收到了一些東西,然後閱讀它。


檢查thisThis exception is mainly used by data input streams to signal end of stream.Note that many other input operations return a special value on end of stream rather than throwing an exception.

+0

正是!該文件已發送,但我無法捕獲它。 – 2014-12-03 11:27:12

+0

你可以建議我們如何捕捉它? – 2014-12-03 11:31:54

+0

正如這個[答](http://stackoverflow.com/a/18451336/2895833)建議,你應該添加一個適當的終止條件 – Xipo 2014-12-03 11:34:25

0

您是否獲得了文件?

public static void receiveFile(String fileName) { 
     boolean recieving = true; //new 
     while(recieving){ //new 
     try { 
     int bytesRead; 
     InputStream in = sock.getInputStream(); 
     DataInputStream clientData = new DataInputStream(in); 
     fileName = clientData.readUTF(); 
     OutputStream output = new FileOutputStream(("received_from_server_")); 
     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(); 
     in.close(); 

     System.out.println("File "+fileName+" received from Server."); 
    } catch (EOFException e){ // new 
     Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex); 
     recieving = false; 
    } catch (IOException ex) { 
     Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    } //new 
} 
+0

試過了,似乎沒有工作。無法接收文件。 – 2014-12-03 12:07:30