进阶day11-网络编程_TCP死循环文件上传的实现

This commit is contained in:
2026-03-27 10:35:55 +08:00
parent f726ca5078
commit b6308288a4
6 changed files with 95 additions and 0 deletions

BIN
1.jpg

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 MiB

After

Width:  |  Height:  |  Size: 51 KiB

BIN
2.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

BIN
3.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
4.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

View File

@@ -0,0 +1,47 @@
package com.inmind.dead_circle_upload04;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/*
文件上传客户端的实现步骤:
1.创建字节输入流读取图片的字节数据
2.创建客户端对象指定服务器的IP和端口
3.获取客户端的字节输出流,将图片的字节数据边读边写,作为请求数据,发送给服务器
4.获取客户端的字节输入流,接收服务器的响应数据
5.资源释放
*/
public class TcpUploadClientDemo06 {
public static void main(String[] args) throws IOException {
//1.创建字节输入流读取图片的字节数据
FileInputStream fis = new FileInputStream("4.jpg");
//2.创建客户端对象指定服务器的IP和端口
Socket client = new Socket("192.168.22.51", 10002);
OutputStream os = client.getOutputStream();//发送请求数据
byte[] buf = new byte[1024];
int len;
//3.获取客户端的字节输出流,将图片的字节数据边读边写,作为请求数据,发送给服务器
while ((len = fis.read(buf)) != -1) {
os.write(buf,0,len);
}
//通知服务端,请求数据发送结束了
fis.close();
System.out.println("客户端上传了图片");
client.shutdownOutput();
//4.获取客户端的字节输入流,接收服务器的响应数据
InputStream is = client.getInputStream();
while ((len = is.read(buf)) != -1) {
System.out.println(new String(buf, 0, len));
}
System.out.println("客户端接收到了响应的结果");
//5.资源释放
client.close();
}
}

View File

@@ -0,0 +1,48 @@
package com.inmind.dead_circle_upload04;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/*
文件上传的服务端的实现步骤:
1.创建一个服务端对象,接收请求
2.获取客户端socket对象的字节输入流接收请求数据图片字节数据
3.创建字节输出流,边读边写到硬盘中
4.获取客户端的socket对象字节输出流发送响应数据上传成功
5.资源释放
*/
public class TcpUploadServerDemo06 {
public static void main(String[] args) throws IOException {
//1.创建一个服务端对象,接收请求
ServerSocket server = new ServerSocket(10002);
System.out.println("服务端启动了");
while (true) {
Socket clientSocket = server.accept();
System.out.println(clientSocket.getInetAddress().getHostAddress());
//2.获取客户端socket对象的字节输入流接收请求数据图片字节数据
InputStream is = clientSocket.getInputStream();
byte[] buf = new byte[1024];
int len;
//3.创建字节输出流,边读边写到硬盘中
FileOutputStream fos = new FileOutputStream("D:\\io_test\\upload\\"+System.currentTimeMillis()+".jpg");
while ((len = is.read(buf)) != -1) {
fos.write(buf,0,len);
}
fos.close();
System.out.println("服务器保存了上传的图片");
//4.获取客户端的socket对象字节输出流发送响应数据上传成功
OutputStream os = clientSocket.getOutputStream();
os.write("上传成功".getBytes());
System.out.println("服务器响应了结果给客户端");
//5.资源释放
clientSocket.close();
// server.close();
}
}
}