java使用Socket实现TCP协议的excel文件从服务器下载到本机写出简单的完整代码需要服务器端和客户端
时间: 2024-10-15 18:25:30 浏览: 29
在Java中,使用Socket实现TCP协议下载Excel文件涉及到两个部分:服务器端和客户端。首先我会分别展示这两个部分的简单代码示例:
### 服务器端 (Server.java)
```java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static final int PORT = 8080; // 服务器监听的端口
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server started on port " + PORT);
while (true) { // 永久循环等待连接
Socket clientSocket = serverSocket.accept();
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String request = in.readLine(); // 获取请求行
if ("GET /file.xls HTTP/1.1".equals(request)) { // 如果请求是要下载Excel文件
sendFile(out, "file.xls"); // 发送文件
} else {
out.println("HTTP/1.1 404 Not Found");
out.flush();
}
} finally {
clientSocket.close();
}
}
}
private static void.sendFile(PrintWriter out, String fileName) {
File file = new File(fileName);
byte[] data = Files.readAllBytes(file.toPath());
out.print("Content-Type: application/vnd.ms-excel\n"); // 设置Content-Type
out.print("Content-Disposition: attachment; filename=\"" + fileName + "\"\n");
out.print("Content-Length: " + data.length + "\n\n"); // 首部信息
out.write(data); // 传送数据
out.flush();
}
}
```
### 客户端 (Client.java)
```java
import java.io.*;
import java.net.URL;
public class Client {
public static void main(String[] args) throws IOException {
URL url = new URL("tcp://localhost:8080/file.xls"); // 使用TCP连接URL
InputStream inputStream = url.openStream(); // 创建输入流
try (BufferedInputStream in = new BufferedInputStream(inputStream);
FileOutputStream outputStream = new FileOutputStream("received_file.xls")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} finally {
inputStream.close();
outputStream.close();
}
System.out.println("File downloaded successfully!");
}
}
```
在这个例子中,服务器端创建了一个监听特定端口的ServerSocket,并处理来自客户端的请求。当接收到请求下载Excel文件时,它将文件内容发送给客户端。
客户端通过TCP连接访问服务器的指定路径并获取Excel文件,然后保存到本地。
注意这只是一个基础的示例,实际应用可能需要处理更复杂的错误情况和网络异常。
阅读全文