Java 网络编程 -- 基于TCP实现文件上传

Java TCP 操作基本流程

一、创建服务器
1、指定端口, 使用serverSocket创建服务器
2、阻塞式连接 accept
3、操作:输入流 输出流
4、释放资源

二、创建客户端
1、使用Socket 创建客户端 + 服务器的ip和端口
2、操作:输入流 输出流
3、释放资源

实现文件上传:

客户端上传:
public class FileClient {
	public static void main(String[] args) throws IOException {
		System.out.println("=======client=======");
		// 1、使用Socket 创建客户端+服务端Ip 和端口
		Socket client = new Socket("localhost", 8888);
		// 2、操作:文件拷贝:上传
		InputStream is = new BufferedInputStream(new FileInputStream("src/张飞.jpg"));
		OutputStream os = new BufferedOutputStream(client.getOutputStream());
		byte[] flush = new byte[1024];
		int len = -1;
		while((len = is.read(flush)) != -1) {
			os.write(flush, 0, len);
		}
		os.flush();
		// 4、释放资源
		os.close();
		is.close();
		client.close();
	}
}

服务端接收:
public class FileServer {
	public static void main(String[] args) throws IOException {
		System.out.println("=======server=======");
		// 1、指定端口创建服务器
		ServerSocket server  = new ServerSocket(8888);
		// 2、阻塞式等待连接
		Socket socket = server.accept();
		// 3、操作:文件拷贝:存储
		InputStream is = new BufferedInputStream(socket.getInputStream());
		OutputStream os = new BufferedOutputStream(new FileOutputStream("src/copy.jpg"));
		byte[] flush = new byte[1024];
		int len = -1;
		while((len = is.read(flush)) != -1) {
			os.write(flush, 0, len);
		}
		os.flush();
		// 4、释放资源
		os.close();
		is.close();
		socket.close();
		server.close();
		
	}
}
重视基础,才能走的更远。
原文地址:https://www.cnblogs.com/xzlf/p/12681518.html