Java Socket 文件上传实现
下面是一个完整的 Java Socket 文件上传实现,包括客户端和服务端代码。

服务端代码 (FileServer.java)
import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) {
int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
try (Socket socket = serverSocket.accept();
DataInputStream dis = new DataInputStream(socket.getInputStream());
FileOutputStream fos = new FileOutputStream("received_" + System.currentTimeMillis() + ".txt")) {
// 读取文件名
String fileName = dis.readUTF();
System.out.println("接收文件: " + fileName);
// 读取文件大小
long fileSize = dis.readLong();
System.out.println("文件大小: " + fileSize + " bytes");
// 读取文件内容
byte[] buffer = new byte[4096];
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = dis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
// 显示进度
if (fileSize > 0) {
int progress = (int) ((totalBytesRead * 100) / fileSize);
System.out.print("\r上传进度: " + progress + "%");
}
}
System.out.println("\n文件接收完成: " + fileName);
} catch (IOException e) {
System.err.println("处理客户端连接时出错: " + e.getMessage());
}
}
} catch (IOException e) {
System.err.println("服务器启动失败: " + e.getMessage());
}
}
}
客户端代码 (FileClient.java)
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) {
String serverAddress = "localhost";
int port = 12345;
String filePath = "example.txt"; // 要上传的文件路径
try (Socket socket = new Socket(serverAddress, port);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
FileInputStream fis = new FileInputStream(filePath)) {
// 获取文件信息
File file = new File(filePath);
String fileName = file.getName();
long fileSize = file.length();
// 发送文件名
dos.writeUTF(fileName);
System.out.println("发送文件名: " + fileName);
// 发送文件大小
dos.writeLong(fileSize);
System.out.println("发送文件大小: " + fileSize + " bytes");
// 发送文件内容
byte[] buffer = new byte[4096];
int bytesRead;
long totalBytesSent = 0;
while ((bytesRead = fis.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
totalBytesSent += bytesRead;
// 显示进度
if (fileSize > 0) {
int progress = (int) ((totalBytesSent * 100) / fileSize);
System.out.print("\r上传进度: " + progress + "%");
}
}
dos.flush();
System.out.println("\n文件发送完成: " + fileName);
} catch (UnknownHostException e) {
System.err.println("无法连接到服务器: " + e.getMessage());
} catch (FileNotFoundException e) {
System.err.println("文件未找到: " + e.getMessage());
} catch (IOException e) {
System.err.println("发生I/O错误: " + e.getMessage());
}
}
}
使用说明
-
创建测试文件:在客户端代码同目录下创建一个名为
example.txt的测试文件。 -
运行服务端:先运行
FileServer,它会等待客户端连接。 -
运行客户端:然后运行
FileClient,它会连接到服务端并上传文件。 -
接收文件:服务端会在当前目录下生成一个以时间戳命名的接收文件。
(图片来源网络,侵删)
功能特点
- 显示上传进度百分比
- 支持大文件传输(使用长整型表示文件大小)
- 使用缓冲区提高传输效率
- 异常处理和资源管理
扩展建议
- 多线程处理:服务端可以改为多线程模式,同时处理多个客户端上传
- 文件校验:添加MD5或SHA校验确保文件完整性
- 断点续传:记录上传进度,支持从中断处继续上传
- GUI界面:添加图形用户界面,方便操作
- 安全性:添加SSL/TLS加密传输
这个实现提供了基本的文件上传功能,你可以根据实际需求进行扩展和优化。
