TCP文件上传的实现

Java TCP文件上传的实现

客户端实现代码

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.net.Socket;


/**
 * 熟悉流程
 * 创建客户端
 * 1 使用Socket创建端 + 服务器的地址和端口
 * 2 操作:输入输出流操作
 * 3 释放资源
 * @author ad
 *
 */
public class FileClient {
	public static void main(String[] args) throws Exception {
		System.out.println("-----Client------");
		//1 建立连接:使用Socket创建端 + 服务器的地址和端口
		Socket client = new Socket("localhost", 9999);
		//2 操作:输入输出流操作
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("abc.txt"));
		BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
		int len = -1;
		byte[] flush = new byte[1024];
		while ((len = bis.read(flush)) != -1) {
			bos.write(flush, 0, len);
		}
		bos.flush();
		//3 释放资源
		bos.close();
		bis.close();
		client.close();
	}
}

服务端实现代码

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 熟悉流程
 * 创建服务器
 * 1 使用ServerSocket创建服务器
 * 2 阻塞式等待连接accept
 * 3 操作:输入输出流操作
 * 4 释放资源
 * @author ad
 *
 */
public class FileServer {
	public static void main(String[] args) throws IOException {
		System.out.println("-----Server------");
		// 1 使用ServerSocket创建服务器
		ServerSocket server = new ServerSocket(9999);
		// 2 阻塞式等待连接accept
		Socket client = server.accept();
		System.out.println("一个客户端建立了连接");
		
		// 3 操作:输入输出流操作
		BufferedInputStream dis = new BufferedInputStream(client.getInputStream());
		BufferedOutputStream dos = new BufferedOutputStream(new FileOutputStream("3.txt"));
		int len = -1;
		byte[] flush  = new byte[1024];
		while ((len = dis.read(flush)) != -1) {
			dos.write(flush, 0, len);
		}
		dos.flush();
		System.out.println("上传成功");
		// 4 释放资源
		dis.close();
		dos.close();
		client.close();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值