1,TCP的文件上传:

  1. 服务端

    1. 1.创建服务端
    2. 同意客户端的连接
    3. 得到Socket输入流
    4. 创建文件输出流
    5. 循环读写数据
    6. 得到Socket的输出流写数据
    7. 关闭 ```java public class Tcps {

    public static void main(String[] args) throws IOException {

    //创建服务端对象 ServerSocket serverSocket = new ServerSocket(8888);

    //同意客户端连接 Socket socket = serverSocket.accept();

    //创建服务端输入流 InputStream inputStream = socket.getInputStream();

    //创建服务端文件(输出)保存流; FileOutputStream fileOutputStream = new FileOutputStream(“G:\xxx.png”);

    //新建空数据包接收数据 byte[] bytes = new byte[1024 * 8]; int length; //循环读取数据包的内容,并写入文件的输出流; while ((length = inputStream.read(bytes)) != -1){

    1. fileOutputStream.write(bytes,0,length);

    }

    //创建输出流: OutputStream outputStream = socket.getOutputStream(); outputStream.write(“finish”.getBytes());

    //close outputStream.close(); fileOutputStream.close(); inputStream.close(); socket.close(); serverSocket.close();

    }

}

  1. 2. **客户端**:
  2. 1. 创建客户端
  3. 1. 创建文件输入流
  4. 1. 得到Socket的输出流
  5. 1. 循环读写数据
  6. 1. 得到Socket输入流读取数据
  7. 1. 关闭资源
  8. ```java
  9. public class Tcpc {
  10. public static void main(String[] args) throws IOException {
  11. //创建客户端对象:
  12. Socket socket = new Socket("127.0.0.1", 8888);
  13. //创建客户端输入的文件流;
  14. FileInputStream fileInputStream = new FileInputStream("G:\\xxx\\xxx2.png");
  15. //创建输出流
  16. OutputStream outputStream = socket.getOutputStream();
  17. //新建空数据包
  18. byte[] bytes = new byte[1024 * 8];
  19. int len;
  20. //循环读取文件io传来的数据,并写入向服务端输出的流;
  21. while ((len = fileInputStream.read(bytes)) != -1){
  22. outputStream.write(bytes,0,len);
  23. }
  24. //********
  25. //关闭输出流,以便让服务端的读取停止等待;
  26. socket.shutdownOutput();
  27. //创建输入流
  28. InputStream inputStream = socket.getInputStream();
  29. //新建空数据包
  30. byte[] bytes1 = new byte[1024 * 8];
  31. //获取读取的数据长度
  32. int len2 = inputStream.read(bytes1);
  33. System.out.println("c:"+new String(bytes,0,len2));
  34. //close
  35. inputStream.close();
  36. outputStream.close();
  37. fileInputStream.close();
  38. socket.close();
  39. }
  40. }

2,解决服务端无法停止的问题:

image.png

  1. 客户端将输出流(Output)关闭即可:就能解决服务端的输入流等待问题;

    1. socket.shutdownOuput();

    3,解决文件重名的问题:

  2. 时间戳:currentTImeMillis();

    1. String filename = UUID.randomUUID().toString();
    2. FileOutputStream fileOutputStream = new FileOutputStream("G:\\xxx"+filename+".png");