7.TCP文件上传实现
先把文件复制到根目录:
![](https://img2020.cnblogs.com/blog/1697640/202003/1697640-20200330180308462-2116115919.png)
![](https://img2020.cnblogs.com/blog/1697640/202003/1697640-20200330180403687-1208571836.png)
客户端:
1 package com.Inet.lesson2; 2 3 import java.io.*; 4 import java.net.InetAddress; 5 import java.net.Socket; 6 7 public class TcpClientDemo02 { 8 public static void main(String[] args) throws Exception { 9 //1.创建一个Socket连接 10 Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000); 11 //2.创建一个输出流 12 OutputStream os = socket.getOutputStream(); 13 //3.读取文件 14 FileInputStream fis = new FileInputStream(new File("girl.jpg")); 15 //4.写出文件 16 byte[] buf = new byte[1024]; 17 int len; 18 while ((len = fis.read(buf)) != -1) { 19 os.write(buf, 0, len); 20 } 21 22 //通知服务器,我已经结束了 23 socket.shutdownOutput();//我已经传输完了 24 25 //确定服务器接收完毕,才能够断开连接 26 InputStream inputStream = socket.getInputStream(); 27 //String byte[] 28 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 29 30 byte[] buf2 = new byte[1024]; 31 int len2; 32 while ((len2 = inputStream.read(buf2)) != -1) { 33 baos.write(buf2, 0, len2); 34 } 35 System.out.println(baos.toString()); 36 37 //5.关闭资源,先开后关 38 baos.close(); 39 inputStream.close(); 40 fis.close(); 41 os.close(); 42 socket.close(); 43 } 44 }
服务器端:
1 package com.Inet.lesson2; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 import java.net.ServerSocket; 8 import java.net.Socket; 9 10 public class TcpServerDemo02 { 11 public static void main(String[] args) throws Exception { 12 //1.创建服务 13 ServerSocket serverSocket = new ServerSocket(9000); 14 //2.监听客户端的连接 15 Socket socket = serverSocket.accept();//阻塞式监听,会一直监听(等待客户端连接) 16 //3.获取输入流 17 InputStream is = socket.getInputStream(); 18 19 //4.文件输出 20 FileOutputStream fos = new FileOutputStream(new File("receive.jpg")); 21 22 byte[] buffer = new byte[1024]; 23 int len; 24 while ((len = is.read(buffer)) != -1) { 25 fos.write(buffer, 0, len); 26 } 27 28 //通知客户端我接收完毕了 29 OutputStream os = socket.getOutputStream(); 30 os.write("我接受完毕了,你可以断开了".getBytes()); 31 32 //关闭资源 33 fos.close(); 34 is.close(); 35 socket.close(); 36 serverSocket.close(); 37 38 } 39 }
测试:
1.先开服务器端,等待接收
2.打开客户端