java使用Socket实现TCP协议的excel文件从服务器上传在上传前基于字符流将文件读取和下载在下载后基于字符流文件的写入到本机的开发实现写出完整代码
时间: 2024-10-10 08:02:42 浏览: 40
C++利用网络套接字Socket实现协议HTTP下载文件的源代码
在Java中,使用Socket实现TCP协议上传Excel文件并基于字符流处理文件操作可以分为以下几个步骤:
首先,我们需要创建一个ServerSocket监听客户端连接:
```java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class FileUploaderServer {
private static final int PORT = 8000; // 设置服务器端口号
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server is running on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
handleClientConnection(clientSocket);
}
}
private static void handleClientConnection(Socket socket) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
// 接收文件数据并保存到临时文件
String line;
StringBuilder fileContent = new StringBuilder();
while ((line = in.readLine()) != null) {
fileContent.append(line);
}
// 将接收的内容写入本地文件
saveToTempFile(fileContent.toString());
// 发送确认信息给客户端
out.println("File uploaded successfully!");
} catch (IOException e) {
e.printStackTrace();
} finally {
socket.close();
}
}
private static void saveToTempFile(String content) {
File tempFile = File.createTempFile("temp", ".xlsx"); // 创建临时文件
try (FileWriter writer = new FileWriter(tempFile)) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Temporary file saved: " + tempFile.getAbsolutePath());
}
}
```
然后,在客户端,我们可以使用Socket发起请求并发送文件内容:
```java
import java.io.*;
import java.net.Socket;
public class FileUploaderClient {
private static final String SERVER_IP = "localhost"; // 服务器地址
private static final int PORT = 8000; // 服务器端口号
public static void main(String[] args) {
Socket socket = new Socket(SERVER_IP, PORT);
try {
// 读取本地文件内容
FileInputStream fis = new FileInputStream("local_file.xlsx");
byte[] data = new byte[(int) fis.getChannel().size()];
fis.read(data);
// 将文件内容转换为字符串并发送到服务器
String fileContent = new String(data);
PrintWriter out = new PrintWriter(socket.getOutputStream());
for (String line : fileContent.split("\n")) {
out.println(line);
}
// 等待服务器响应
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(in.readLine()); // "File uploaded successfully!"
// 文件上传完成,关闭流
fis.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
socket.close();
}
}
}
```
这个例子中,我们假设Excel文件已经存在,并通过简单的文本方式上传和下载。实际应用中,你需要额外处理二进制文件,比如使用`DataOutputStream`和`FileChannel`。
阅读全文