文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!
import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * @author ServerTCP * @date 2020/4/25 10:51 上午 */ public class ServerTCP { public static void main(String[] args) throws IOException { System.out.println("服务启动,等待连接中"); //创建ServerSocket对象,绑定端口,开始等待连接 ServerSocket ss = new ServerSocket(8888); //接受accept方法,返回socket对象 Socket server = ss.accept(); //获取输入对象,读取文件 BufferedInputStream bis = new BufferedInputStream(server.getInputStream()); //保存到本地 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.txt")); //创建字节数组 byte[] b = new byte[1024 * 8]; //读取字符数组 int len; while ((len = bis.read(b)) != -1) { bos.write(b, 0, len); } //关闭资源 bos.close(); bis.close(); server.close(); System.out.println("上传成功"); } }
import java.io.*; import java.net.Socket; /** * @author ClientTCP * @date 2020/4/25 10:58 上午 */ public class ClientTCP { public static void main(String[] args) throws IOException { //创建输入流 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("in.txt")); //创建Socket Socket client = new Socket("127.0.0.1", 8888); //输出流 BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream()); //写出数据 byte[] b = new byte[1024 * 8]; int len; while ((len = bis.read(b)) != -1) { bos.write(b, 0, len); bos.flush(); } System.out.println("文件已上传"); //关闭资源 bos.close(); client.close(); bis.close(); System.out.println("文件上传完成"); } }
以及勤劳的自己