Java learning line: day14 network programming

itread01 2020-11-06 01:18:07
java learning line day14 day


>** Experience :** > I am a self-taught java About to graduate from college > The purpose of summarizing notes is to make yourself better understand and deepen my impression . It may not be so beautiful , I wish I could understand it > * All the files and source code are open source in **GitHub**: [**https://github.com/kun213/JavaNotes**](https://github.com/kun213/JavaNotes/) Yes *. I hope we can refuel together , Learn together , Communicate together ## day14 【 Network programming 】 @[toc]( Today's learning content -2020.10.16) ## One 、 Introduction to network programming ### 1.1 You can tell the structure of the software **C/S Structure ** : Its full name is Client/Server Structure , It refers to the client and server structure . Common programs are QQ、 Xunlei and other software . **B/S Structure ** : Its full name is Browser/Server Structure , Browser and server architecture . Common browsers are Google 、 Foxes, etc . ### 1.2 You can say UDP and TCP Protocol features - **TCP**: Transmission control protocol (Transmission Control Protocol).TCP The agreement is ** Connection oriented ** Communication protocol for , Before the data is transmitted , Establish a logical connection between the sender and the receiver , And then transmit the data , It provides reliable error free data transmission between two computers . - Three handshakes :TCP In the agreement , In the preparation stage of transmitting data , Three interactions between client and server , To ensure the reliability of the connection . - The first handshake , The client sends a connection request to the server , Wait for the server to confirm . - The second handshake , The server sends back a response to the client , Notify the client that a connection request has been received . - The third handshake , The client sends the confirmation information to the server again , Confirm the connection . The whole interaction process is shown in the figure below ![](https://img-blog.csdnimg.cn/img_convert/6e82960b9e2824bc62c8931f70f96e27.png) Complete three handshakes , After the connection is established , The client and server can start data transfer . Because of this connection oriented feature ,TCP The protocol can guarantee the security of the transmitted data , So it's widely used , For example, downloading files 、 Browsing the web, etc . - **UDP**: User datagram protocol (User Datagram Protocol).UDP The agreement is a ** Facing no connection ** Agreement of . When transmitting data , There is no need to establish a connection , No matter whether the other side service is started or not , Directly put the information 、 Data sources and destinations are encapsulated in data packets , Direct transmission . The size of each packet is limited to 64k Within . It's an unreliable protocol , Because there's no connection , So the transmission speed is fast , But it's easy to lose data . In daily use , For example, video conferencing 、QQ Chat, etc . The maximum amount of data transmitted each time is 64kb. ## Two 、TCP Communication protocol ### 2.1 You can say TCP Two common class names under the protocol ** stay Java in , Two classes are provided to implement TCP Communication program :** - Client :`java.net.Socket` Class representation . establish `Socket` thing , Send a connection request to the server , The server responds to the request , The two establish a connection and begin to communicate . - Server-side :`java.net.ServerSocket` Class representation . establish `ServerSocket` thing , It is equivalent to opening a service , And wait for the client to connect . ### 2.2 How to write TCP Protocol string data transfer program Realize TCP Communication client program : ```java /** * Realize TCP Communication client program * * java.net.Socket Implement the socket object of the client , Connecting objects * * demand : Client program and server program realize data exchange * * Implementation steps : * 1: establish Socket thing ( Actively connect to the server ) * Socket(String host, int port) * * 2: OutputStream getOutputStream() * Returns the byte output stream in the socket * Method write Write data , Write to the server * * 3: InputStream getInputStream() * Returns the byte input stream in the socket * Method read Read data , It reads the data sent back by the server * * 4: Releasing resources */ public class TCPClient { public static void main(String[] args)throws IOException { // establish Socket thing ( Actively connect to the server ) Socket socket = new Socket("127.0.0.1",9000); //OutputStream getOutputStream() OutputStream out = socket.getOutputStream(); // Byte stream method to write data out.write(" Hello server ".getBytes());// It's not in the file , Written to the server InputStream in = socket.getInputStream();// Get byte input stream byte[] bytes = new byte[1024]; int len = in.read(bytes);// Client input stream , Read the data sent back from the server System.out.println(new String(bytes,0,len)); // Releasing resources //out.close(); socket.close(); } } ``` Realize TCP Communication server program : ```java /** * Realize TCP Communication server program * 192.168.27.95 * java.net.ServerSocket Realize TCP Server socket object in protocol * * Realize TCP Server program steps : * 1: establish ServerSocket thing * ServerSocket(int port) Port number * * 2: Waiting for the client to connect , If there is no client connection , Always wait for * ServerSocket Class method accept() agree! * Method accept() The return value is Socket thing ( Client connection object , Contains the client IP) * * 3: Socket Get in place tuple output stream from object * OutputStream getOutputStream() * Method write Writing materials , Write to client * * 4: Socket Object to get in place tuple input stream * InputStream getInputStream() * Method read Read data , Read the data from the client * * 5: Releasing resources */ public class TCPServer { public static void main(String[] args)throws IOException { // establish ServerSocket thing ServerSocket server = new ServerSocket(9000); //ServerSocket Class method accept() agree! Socket socket = server.accept(); //System.out.println(socket); // Use the client connection to get the object , Input stream InputStream in = socket.getInputStream(); //in Input stream method read() Read the data sent by the client byte[] bytes = new byte[1024]; //len The number of bytes read is returned int len = in.read(bytes); System.out.println(new String(bytes,0,len)); //Socket Client object , Get byte output stream OutputStream out = socket.getOutputStream(); out.write(" received !".getBytes());// Server output stream , Write back to the client // Releasing resources socket.close(); server.close(); } } ``` ### 2.3 understand TCP File upload cases under the agreement ![](https://img-blog.csdnimg.cn/img_convert/baf7cd559981cfdca3bcfca342ac4c46.png) Realize image upload client : ```java /** * Realize TCP Image upload client * Implementation steps : * 1: establish Socket thing , Connect to the server * 2: FileInputStream Read mm.jpg Array of bytes * 3: Socket Object gets the byte output stream * Array of bytes , To the output stream , Write to the server * 4: Socket Object gets the byte input stream * All the pictures have been transferred * Input stream , Read the prompt information from the server " Upload successful " * * Client method Socket: shutdownOutput() Terminate the output stream of the connected object , * At the same time, keep up with TCP Termination sequence * 5: Releasing resources */ public class TCPClient { public static void main(String[] args) throws IOException{ //1: establish Socket thing , Connect to the server Socket socket = new Socket("127.0.0.1",9000); //2: Its own byte input stream , Read the picture mm.jpg FileInputStream fis = new FileInputStream("e:/msh.jpg"); //3: Socket Object gets the byte output stream OutputStream out = socket.getOutputStream();// Any information , Write to the server byte[] bytes = new byte[1024]; int len = 0; //fis Read the end of the file ,JVM return read() -1 while ((len = fis.read(bytes))!=-1){ out.write(bytes,0,len); } // Tell the server , No more information , Don't read , The server sends TCP The terminator of socket.shutdownOutput(); //4:Socket Object gets the byte input stream InputStream in = socket.getInputStream();// Input stream , Read the data from the server len = in.read(bytes); System.out.println(" Server prompt ::"+new String(bytes,0,len)); socket.close(); } } ``` Realize image upload server : ```java /** * Realize image upload server * Implementation steps : * 1: Create objects ServerSocket Binding port * 2: Socket accept() Method to wait for the client to connect * 3: Socket thing , Get byte input stream , Read the bytes of the image sent by the client * 4: Create a byte output stream , Read the picture , Write e:/upload * 5: Socket thing , Get byte output stream ," Upload successful " Write back to the client * * bug: * 1: Demonstrated 2 Time , Why is there only one folder in the file , Cover with the same name * a: 1.jpg * b: 1.jpg * * 2: The client failed to receive the upload from the server // Tell the server , No more information , Don't read , The server sends TCP The terminator of */ public class TCPServer { public static void main(String[] args) throws IOException{ //1: Create objects ServerSocket Binding port ServerSocket server = new ServerSocket(9000); // 2: Socket accept() Method to wait for the client to connect Socket socket = server.accept(); //3: Socket thing , Get byte input stream , Read the bytes of the image sent by the client InputStream in = socket.getInputStream(); //4: Create a byte output stream , Read the picture , Write e:/upload // Uploaded files , Rename , Get the current date Convert to string String filename = new SimpleDateFormat("yyyyMMddHHmmssssss").format(Calendar.getInstance().getTime())+".jpg"; FileOutputStream fos = new FileOutputStream("e:/upload/"+filename); byte[] bytes = new byte[1024]; int len = 0; //read() Reading is a picture written by the client !! while ( (len = in.read(bytes))!=-1){ fos.write(bytes,0,len); } //5: Socket thing , Get byte output stream ," Upload successful " Write back to the client OutputStream out= socket.getOutputStream(); out.write(" Upload successful !".getBytes()); socket.close(); server.close(); } } ``` ------ *** This is my public number , I hope you can pay attention to , Let's be our best selves together . I will also share my self-study video on it , For everyone to learn together .*** ![CodeBull](https://img-blog.csdnimg.cn/20201008185633816.jpg#pic_center)
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云