我需要更改此代码,以便在它当前只发送一个文件时发送图像文件目录,我的主要目标是让它请求一个目录,然后发送该目录中的所有文件(图像文件)到服务器然后我需要它来显示我目前拥有的代码有多少数据:
客户端:
package sockets;
import java.net.*;
import java.io.*;
public class Client {
public static void main (String [] args ) throws IOException {
int filesize=1022386;
int bytesRead;
int currentTot = 0;
Socket socket = new Socket("127.0.0.1",6789);
byte [] bytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("copy.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead;
System.out.println("The Size of the data transferred is " + bytesRead + " Bytes");
do {
bytesRead =
is.read(bytearray, currentTot, (bytearray.length-currentTot));
if(bytesRead >= 0) currentTot += bytesRead;
} while(bytesRead > -1);
bos.write(bytearray, 0 , currentTot);
bos.flush();
bos.close();
socket.close();
}
}
服务器:
package sockets;
import java.net.*;
import java.io.*;
public class Server {
public static void main (String [] args ) throws IOException {`
ServerSocket serverSocket = new ServerSocket(6789);
Socket socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
File transferFile = new File ("Orders.txt");
byte [] bytearray = new byte [(int)transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
bin.read(bytearray,0,bytearray.length);
OutputStream os = socket.getOutputStream();
System.out.println("Sending Files...");
os.write(bytearray,0,bytearray.length);
os.flush();
socket.close();
System.out.println("File transfer complete");
}
}
谢谢
答案 0 :(得分:1)
迭代所选目录中的所有文件,并获取您要发送的所有已知图像扩展名。
Here's an example用于迭代文件。
然后,将每个文件中的字节从客户端流式传输到服务器。
我建议使用FTP将您的文件作为已建立的协议发送到您的服务器,以解决此类问题。
答案 1 :(得分:0)
无法完全发送目录。您有两个选择: