套接字,java发送文件服务器客户端

套接字,java发送文件服务器客户端

问题描述:

我想通过套接字发送文件。 “服务器”位于另一台计算机上,而另一台计算机上则位于另一台计算机上。该文件可以来回服务器和客户端,但只能在他们当前的目录中。我所采取的方法是通过使用文件输入流并将文件写入文件输出流neverthelees这不工作,据我了解..有没有另一种方式来通过套接字发送文件?套接字,java发送文件服务器客户端

这是我的代码这里有什么可能是错的?

public class Copy { 

    private ListDirectory dir; 
    private Socket socket; 

    public Copy(Socket socket, ListDirectory dir) { 
     this.dir = dir; 
     this.socket = socket; 
    } 

    public String getCopyPath(String file) throws Exception { 
     String path = dir.getCurrentPath(); 
     path += "\\" + file; 
     return path; 

    } 

    public void copyFileToClient(String file, String destinationPath) 
    throws Exception { 

     byte[] receivedData = new byte[8192]; 
     BufferedInputStream bis = new BufferedInputStream(
        new FileInputStream(getCopyPath(file))); 
     String findDot = file; 
     String extension = ""; 

     for (int i = 0; i < findDot.length(); i++) { 
      String dot = findDot.substring(i, i + 1); 
      if (dot.equals(".")) { 
       extension = findDot.substring(i + 1); 
      } 
     } 
     if (extension.equals("")) { 
      extension = "txt"; 
     } 
     BufferedOutputStream bos = new BufferedOutputStream(
        new FileOutputStream(new File(destinationPath + "\\" 
       + "THECOPY" + "." + extension))); 

     int len; 

     while ((len = bis.read(receivedData)) > 0) { 

      bos.write(receivedData, 0, len); 
     } 
     //  in.close(); 
     bis.close(); 
     //  output.close(); 
     bos.close(); 

    } 

    // public static void main(String args[]) throws Exception { 
    //  Copy copy = new Copy(); 
    //  System.out.print(copy.getCopyPath("a")); 
    // } 

} 

而且一些客户端代码:

... 

DataOutputStream outToServer = new DataOutputStream(
     clientSocket.getOutputStream()); 
BufferedReader inFromServer = new BufferedReader(
     new InputStreamReader(clientSocket.getInputStream())); 
boolean exit = false; 

else if (sentence.length() > 3 && sentence.substring(0, 3).equals("get")) { 
     String currPath = dir.getCurrentPath(); 
     outToServer.writeBytes(sentence + "_" + currPath + "\n"); 

} else { 

... 
+0

什么意思是“不起作用”?请更详细地说明你的问题。 – 2011-05-22 13:06:29

copyFileToClient方法使用一个FileInputStream和FileOutputStream中直接,即它不什么/来自客户端的所有转让,只能从一个本地文件到另一个。如果您想远程管理服务器上的文件,但没有任何帮助在不同计算机之间发送数据的情况,这很好。

您必须以某种方式通过Socket的OutputStream/InputStream发送数据 - 即在发送端使用FileInputStream,在接收端使用FileOutputStream。

+2

+1 - 提高阅读能力! – 2011-05-22 13:26:27