我想通过套接字发送文件。 “服务器”位于另一台计算机上,而不是我的计算机上,客户端也位于另一台计算机上。该文件可以在服务器和客户端之间往返,但只能在它们的当前目录中。我到目前为止所采取的方法是使用文件输入流并将文件写入文件输出流,但据我所知,这不起作用。是否有另一种方法可以通过套接字发送文件?
这是我的代码,这里可能有什么问题?
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 {
...
最佳答案
您的copyFileToClient方法直接使用FileInputStream和FileOutputStream,即它根本不向客户端传输任何内容或从客户端传输任何内容,而只是从一个本地文件传输到另一个本地文件。如果您想远程管理服务器上的文件,这很好,但对于在不同计算机之间发送数据没有帮助。
您必须以某种方式通过 Socket 的 OutputStream/InputStream 发送数据 - 即在发送端使用 FileInputStream,在接收端使用 FileOutputStream。
关于java - 套接字,java发送文件服务器客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6087386/