• 例题2:客户端发送文件给服务器端,服务端将文件保存在本地 ```java package com.atguigu.java2;

    import org.junit.Test;

    import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket;

    /**

    • 实现TCP的网络编程
    • 例题2:客户端发送文件给服务器端,服务端将文件保存在本地
    • @author Dxkstart
    • @create 2021-06-04 18:50 */ public class TCPTest2 {

      @Test public void client(){

      1. Socket socket = null;
      2. OutputStream os = null;
      3. FileInputStream fis = null;
      4. try {
      5. //1.
      6. socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
      7. //2.
      8. os = socket.getOutputStream();
      9. //3.
      10. fis = new FileInputStream(new File("鸣人.jpg"));
      11. //4.
      12. byte[] buffer = new byte[1024];
      13. int len;
      14. while ((len = fis.read(buffer)) != -1){
      15. os.write(buffer,0,len);
      16. }
      17. } catch (IOException e) {
      18. e.printStackTrace();
      19. } finally {
      20. try {
      21. if(fis != null) {
      22. fis.close();
      23. }
      24. } catch (IOException e) {
      25. e.printStackTrace();
      26. }
      27. try {
      28. if(os != null) {
      29. os.close();
      30. }
      31. } catch (IOException e) {
      32. e.printStackTrace();
      33. }
      34. try {
      35. if(socket != null) {
      36. socket.close();
      37. }
      38. } catch (IOException e) {
      39. e.printStackTrace();
      40. }
      41. }

      }

      @Test public void server(){

      1. ServerSocket ss = null;
      2. Socket socket = null;
      3. InputStream is = null;
      4. FileOutputStream fos = null;
      5. try {
      6. //1.
      7. ss = new ServerSocket(9090);
      8. //2.
      9. socket = ss.accept();
      10. //3.
      11. is = socket.getInputStream();
      12. //4.
      13. fos = new FileOutputStream(new File("鸣人2.jpg"));
      14. //5.
      15. byte[] buffer = new byte[1024];
      16. int len;
      17. while ((len = is.read(buffer)) != -1){
      18. fos.write(buffer,0,len);
      19. }
      20. } catch (IOException e) {
      21. e.printStackTrace();
      22. } finally {
      23. try {
      24. if(fos != null) {
      25. fos.close();
      26. }
      27. } catch (IOException e) {
      28. e.printStackTrace();
      29. }
      30. try {
      31. if(is != null) {
      32. is.close();
      33. }
      34. } catch (IOException e) {
      35. e.printStackTrace();
      36. }
      37. try {
      38. if(socket != null) {
      39. socket.close();
      40. }
      41. } catch (IOException e) {
      42. e.printStackTrace();
      43. }
      44. try {
      45. if(ss != null) {
      46. ss.close();
      47. }
      48. } catch (IOException e) {
      49. e.printStackTrace();
      50. }
      51. }

      } }

    ```