2011-01-14 23 views
32

我已經實現了簡單的TCP服務器和TCP客戶端類,它們可以將消息從客戶端發送到服務器,並且消息將在服務器端轉換爲大寫,但我如何實現從服務器到客戶端的傳輸文件並將文件從客戶端上傳到服務器。下面的代碼是我得到的。如何實現使用java套接字在客戶端和服務器之間傳輸文件

TCPClient.java

 import java.io.*; 
     import java.net.*; 
     import java.util.Scanner; 

class TCPClient { 

public static void main(String args[]) throws Exception { 
     int filesize=6022386; 
     int bytesRead; 
     int current = 0; 
    String ipAdd=""; 
    int portNum=0; 
    boolean goes=false; 
    if(goes==false){ 
    System.out.println("please input the ip address of the file server"); 
    Scanner scan=new Scanner(System.in); 
    ipAdd=scan.nextLine(); 
    System.out.println("please input the port number of the file server"); 
    Scanner scan1=new Scanner(System.in); 
    portNum=scan1.nextInt(); 
    goes=true; 
    } 
    System.out.println("input done"); 
    int timeCount=1; 
    while(goes==true){ 
    //System.out.println("connection establishing"); 

    String sentence=""; 
    String modifiedSentence; 

    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
      System.in)); 

    Socket clientSocket = new Socket(ipAdd, portNum); 
    //System.out.println("connecting"); 
    //System.out.println(timeCount); 
    if(timeCount==1){ 
    sentence="set"; 
    //System.out.println(sentence); 


    } 
    if(timeCount!=1) 
     sentence = inFromUser.readLine(); 
      if(sentence.equals("close")) 
       clientSocket.close(); 
      if(sentence.equals("download")) 
      { 
       byte [] mybytearray = new byte [filesize]; 
       InputStream is = clientSocket.getInputStream(); 
       FileOutputStream fos = new FileOutputStream("C:\\users\\cguo\\kk.lsp"); 
       BufferedOutputStream bos = new BufferedOutputStream(fos); 
       bytesRead = is.read(mybytearray,0,mybytearray.length); 
       current = bytesRead; 
       do { 
    bytesRead = 
     is.read(mybytearray, current, (mybytearray.length-current)); 
    if(bytesRead >= 0) current += bytesRead; 
} while(bytesRead > -1); 

bos.write(mybytearray, 0 , current); 
bos.flush(); 
long end = System.currentTimeMillis(); 
//System.out.println(end-start); 
bos.close(); 
clientSocket.close(); 
      } 
      // if(sentence.equals("send")) 
       // clientSocket. 
    timeCount--; 
    //System.out.println("connecting1"); 
    DataOutputStream outToServer = new DataOutputStream(clientSocket 
      .getOutputStream()); 

    BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
      clientSocket.getInputStream())); 


    //System.out.println("connecting2"); 
    //System.out.println(sentence); 
    outToServer.writeBytes(sentence + "\n"); 

    modifiedSentence = inFromServer.readLine(); 

    System.out.println("FROM SERVER:" + modifiedSentence); 

    clientSocket.close(); 

} 
} 

}


TCPServer.java

  import java.io.*; 
     import java.net.*; 

    class TCPServer { 
public static void main(String args[]) throws Exception { 

    Socket s = null; 

    int firsttime=1; 


    while (true) { 
     String clientSentence; 
    String capitalizedSentence=""; 

     ServerSocket welcomeSocket = new ServerSocket(3248); 
     Socket connectionSocket = welcomeSocket.accept(); 

      //Socket sock = welcomeSocket.accept(); 


     BufferedReader inFromClient = new BufferedReader(
       new InputStreamReader(connectionSocket.getInputStream())); 

     DataOutputStream outToClient = new DataOutputStream(
       connectionSocket.getOutputStream()); 

     clientSentence = inFromClient.readLine(); 
     //System.out.println(clientSentence); 
        if(clientSentence.equals("download")) 
        { 
         File myFile = new File ("C:\\Users\\cguo\\11.lsp"); 
    byte [] mybytearray = new byte [(int)myFile.length()]; 
    FileInputStream fis = new FileInputStream(myFile); 
    BufferedInputStream bis = new BufferedInputStream(fis); 
    bis.read(mybytearray,0,mybytearray.length); 
    OutputStream os = connectionSocket.getOutputStream(); 
    System.out.println("Sending..."); 
    os.write(mybytearray,0,mybytearray.length); 
    os.flush(); 
    connectionSocket.close(); 
        } 
     if(clientSentence.equals("set")) 
      {outToClient.writeBytes("connection is "); 
      System.out.println("running here"); 
      //welcomeSocket.close(); 
      //outToClient.writeBytes(capitalizedSentence); 
      } 



     capitalizedSentence = clientSentence.toUpperCase() + "\n"; 


    //if(!clientSentence.equals("quit")) 
      outToClient.writeBytes(capitalizedSentence+"enter the message or command: "); 


     System.out.println("passed"); 
     //outToClient.writeBytes("enter the message or command: "); 
     welcomeSocket.close(); 
    System.out.println("connection terminated"); 
    } 
} 

}

所以,TCPServer.java將首先執行,然後執行TCPClien t.java,我嘗試使用TCPServer.java中的if子句來測試用戶的輸入,現在我真的想實現如何從兩面傳輸文件(下載和上傳)。謝謝。

+0

完整的示例在這裏https://github.com/hardeepvicky/Java-FileTransfer – 2017-09-15 07:03:35

回答

24

通過源代碼快速閱讀,似乎你並不遙遠。下面的鏈接應該有所幫助(我做了類似的事情,但爲了FTP)。對於從服務器發送到客戶端的文件,首先使用文件實例和字節數組。然後,將文件讀入字節數組,並將字節數組寫入到與客戶端的InputStream對應的OutputStream中。

http://www.rgagnon.com/javadetails/java-0542.html

編輯:這裏有一個工作超簡約的文件發送者和接收者。確保你瞭解代碼在雙方中的作用。

package filesendtest; 

import java.io.*; 
import java.net.*; 

class TCPServer { 

    private final static String fileToSend = "C:\\test1.pdf"; 

    public static void main(String args[]) { 

     while (true) { 
      ServerSocket welcomeSocket = null; 
      Socket connectionSocket = null; 
      BufferedOutputStream outToClient = null; 

      try { 
       welcomeSocket = new ServerSocket(3248); 
       connectionSocket = welcomeSocket.accept(); 
       outToClient = new BufferedOutputStream(connectionSocket.getOutputStream()); 
      } catch (IOException ex) { 
       // Do exception handling 
      } 

      if (outToClient != null) { 
       File myFile = new File(fileToSend); 
       byte[] mybytearray = new byte[(int) myFile.length()]; 

       FileInputStream fis = null; 

       try { 
        fis = new FileInputStream(myFile); 
       } catch (FileNotFoundException ex) { 
        // 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(); 

        // File sent, exit the main method 
        return; 
       } catch (IOException ex) { 
        // Do exception handling 
       } 
      } 
     } 
    } 
} 

package filesendtest; 

import java.io.*; 
import java.io.ByteArrayOutputStream; 
import java.net.*; 

class TCPClient { 

    private final static String serverIP = "127.0.0.1"; 
    private final static int serverPort = 3248; 
    private final static String fileOutput = "C:\\testout.pdf"; 

    public static void main(String args[]) { 
     byte[] aByte = new byte[1]; 
     int bytesRead; 

     Socket clientSocket = null; 
     InputStream is = null; 

     try { 
      clientSocket = new Socket(serverIP , serverPort); 
      is = clientSocket.getInputStream(); 
     } catch (IOException ex) { 
      // Do exception handling 
     } 

     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

     if (is != null) { 

      FileOutputStream fos = null; 
      BufferedOutputStream bos = null; 
      try { 
       fos = new FileOutputStream(fileOutput); 
       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 
      } 
     } 
    } 
} 

相關

Byte array of unknown length in java

編輯:可以在使用前和轉移後的指紋小文件下面的(使用SHA如果你覺得這是必要的):

public static String md5String(File file) { 
    try { 
     InputStream fin = new FileInputStream(file); 
     java.security.MessageDigest md5er = MessageDigest.getInstance("MD5"); 
     byte[] buffer = new byte[1024]; 
     int read; 
     do { 
      read = fin.read(buffer); 
      if (read > 0) { 
       md5er.update(buffer, 0, read); 
      } 
     } while (read != -1); 
     fin.close(); 
     byte[] digest = md5er.digest(); 
     if (digest == null) { 
      return null; 
     } 
     String strDigest = "0x"; 
     for (int i = 0; i < digest.length; i++) { 
      strDigest += Integer.toString((digest[i] & 0xff) 
        + 0x100, 16).substring(1).toUpperCase(); 
     } 
     return strDigest; 
    } catch (Exception e) { 
     return null; 
    } 
} 
+0

@James:我已經更新了我的代碼,但是,它無法正確接收文件,下載的文件是空的,您可以花些時間請檢查出來。 – starcaller 2011-01-14 04:06:29

相關問題