java使用Socket实现TCP协议的excel文件从服务器下载到本机的开发实现把服务端和客户端全写出来
时间: 2024-10-10 14:08:37 浏览: 24
在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 server = new ServerSocket(PORT);
System.out.println("Server started on port " + PORT);
while (true) {
Socket clientSocket = server.accept(); // 等待客户端连接
handleClient(clientSocket); // 处理每个连接请求
}
}
private static void handleClient(Socket socket) throws IOException {
OutputStream outputStream = socket.getOutputStream();
File fileToServe = new File("path_to_your_excel_file.xlsx"); // 文件路径
FileInputStream fis = new FileInputStream(fileToServe);
byte[] buffer = new byte[(int) fileToServe.length()];
fis.read(buffer);
outputStream.write(buffer);
fis.close();
outputStream.flush();
socket.close();
System.out.println("File sent to client.");
}
}
```
**客户端(Client.java)**
```java
import java.io.*;
import java.net.Socket;
public class Client {
private static final String SERVER_HOST = "localhost"; // 服务器地址
private static final int PORT = 8080; // 服务器监听的端口
public static void main(String[] args) {
try (Socket socket = new Socket(SERVER_HOST, PORT)) {
System.out.println("Connecting to server...");
InputStream inputStream = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("received_excel_file.xlsx");
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
inputStream.close();
socket.close();
System.out.println("Download complete.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文