java使用Socket实现TCP协议的excel文件从服务器下载到本机写出完整的服务器端口和客户端端口代码
时间: 2024-10-14 17:07:36 浏览: 46
Socket通信技术(Java)
在Java中,我们可以使用`java.net.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 = 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();
try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
String fileName = in.readLine(); // 获取文件名
File file = new File(fileName); // 检查文件是否存在
if (file.exists()) {
byte[] bytes = Files.readAllBytes(file.toPath()); // 读取文件内容
out.println(bytes.length); // 发送文件长度
out.flush();
out.write(bytes); // 发送文件数据
out.close();
System.out.println("Sent file: " + fileName);
} else {
out.println("File not found.");
}
} finally {
clientSocket.close();
}
}
}
}
```
**客户端代码(Client.java):**
```java
import java.io.*;
import java.net.*;
public class Client {
private static final int PORT = 8000; // 客户端连接服务器的端口
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", PORT);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
// 通常情况下,从服务器获取文件名
String fileName = in.readLine();
System.out.println("Downloading file: " + fileName);
// 获取文件大小
int fileSize = Integer.parseInt(in.readLine());
byte[] buffer = new byte[fileSize];
// 接收文件
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
System.out.println("Download complete.");
in.close();
out.close();
} catch (IOException e) {
System.err.println("Error downloading file: " + e.getMessage());
}
}
}
```
请注意,这只是一个基础示例,实际应用中你需要处理可能出现的异常,并可能需要添加错误处理和协议头解析等部分。运行时,服务器需要启动 `Server` 类,而客户端则需要启动 `Client` 类并与服务器进行连接。
阅读全文