下面是一个简单的Java程序,用于发送和接收多张图片。在这个程序中,我们通过Socket和ServerSocket实现了一个简单的文件传输服务器和客户端,可以在本地网络中传输多张图片文件。
服务端代码:
java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务端已启动,等待客户端的连接...");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接:" + socket.getRemoteSocketAddress());
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(new BufferedInputStream(is));
String fileName = dis.readUTF();
long fileLength = dis.readLong();
FileOutputStream fos = new FileOutputStream(new File("server_files/" + fileName));
byte[] bytes = new byte[1024];
int length;
while ((length = dis.read(bytes, 0, bytes.length)) != -1) {
fos.write(bytes, 0, length);
fos.flush();
}
System.out.println("文件接收成功:" + fileName);
fos.close();
dis.close();
is.close();
socket.close();
}
}
}
客户端代码:
java
import java.io.*;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8888);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
Path path = Paths.get("client_files/");
Files.createDirectories(path);
File[] files = path.toFile().listFiles();
for (File file : files) {
if (file.isFile()) {
System.out.println("正在发送文件:" + file.getName());
dos.writeUTF(file.getName());
dos.flush();
dos.writeLong(file.length());
dos.flush();
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[1024];
int length = 0;
while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
dos.write(bytes, 0, length);
dos.flush();
}
System.out.println("文件发送成功:" + file.getName());
fis.close();
}
}
dos.close();
os.close();
socket.close();
}
}
在这个程序中,客户端会遍历本地的文件夹,将其中的图片文件发送到服务器;而服务端会接收这些图片并保存到指定目录下。
请注意,上述代码只是一个简单的示例程序。在实际应用程序中,您需要考虑更多的异常处理和安全性问题,例如加密传输、文件大小限制、并发处理、文件名处理等。同时,您也可以对程序进行优化,例如将文件分块传输等。