TCP通信练习3–上传文件有一个img.jpg图片文件 客户端:将本地图片文件上传到服务器。接收服务器的反馈。 服务器:接收客户端上传的图片文件,上传完毕之后给出反馈。完整代码添加注释
时间: 2024-12-08 09:19:35 浏览: 13
在进行TCP通信时,通常我们会使用`java.net.Socket`类来建立连接,并处理数据传输。这里我会给你一个基本的示例,包括客户端和服务器的代码以及必要的注释。首先,确保你了解TCP的基本概念,如套接字(socket)创建、读写操作等。
**客户端(Client.java):**
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
// 创建Socket对象
Socket socket = new Socket("localhost", 8080); // 假设服务器运行在本机的8080端口
try (BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream())) {
// 读取图片文件
File file = new File("img.jpg"); // 图片路径
FileInputStream fis = new FileInputStream(file);
// 获取文件长度
long fileSize = fis.getChannel().size();
// 发送文件信息
out.write(("File size: " + fileSize).getBytes());
byte[] buffer = new byte[1024];
int bytesRead;
// 逐块发送文件内容
while ((bytesRead = fis.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
// 关闭流
fis.close();
out.flush();
// 接收服务器的反馈
System.out.println(new String(in.readAllBytes()));
} finally {
socket.close(); // 关闭连接
}
}
}
```
**服务器(Server.java):**
```java
import java.io.*;
import java.net.*;
public class Server {
private ServerSocket serverSocket;
private Thread listenerThread;
public Server(int port) {
try {
serverSocket = new ServerSocket(port);
listenerThread = new ListenerThread(serverSocket);
listenerThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private class ListenerThread extends Thread {
private Socket clientSocket;
public ListenerThread(ServerSocket ss) {
this.clientSocket = null;
setDaemon(true);
}
@Override
public void run() {
try {
clientSocket = ss.accept();
handleConnection(clientSocket);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void handleConnection(Socket socket) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
// 接收文件大小信息
String fileSizeStr = in.readLine();
long fileSize = Long.parseLong(fileSizeStr.substring("File size: ".length()));
// 检查是否成功接收
byte[] buffer = new byte[(int) fileSize];
int receivedBytes = 0;
while (receivedBytes < fileSize) {
receivedBytes += in.read(buffer, receivedBytes, (buffer.length - receivedBytes));
}
// 存储或处理接收到的文件
File outputFile = new File("receivedImg.jpg");
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(buffer);
fos.close();
// 发送确认信息给客户端
out.println("File uploaded successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Server(8080); // 假定服务器监听8080端口
}
}
```
阅读全文