*1, There are two main problems in network programming: * 1. How to accurately locate one or multi state host (IP) on the network; Locate the specific application (port number) on the host * 2. How to carry out network transmission reliably and efficiently after finding the host * *2, Two elements in network programming: * 1. Corresponding question 1: IP and port number * 2. Corresponding question 2: provide network communication protocol: TCP/IP reference model (application layer, transmission layer, network layer, physical + data link layer) * * *3, Communication elements: Ip and port number * 1.IP: uniquely identifies the computer (communication entity) on the Internet * 2. Use the InetAddress class to represent IP in java * 3.Ip Classification: IpV4 and Ipv6: World Wide Web and LAN * 4. Domain name: www.baidu.com com www.bilibili. Com because the ip address is not easy to remember *Domain names can be complex IP addresses that we don't have to remember *Enter the domain name on the search engine, such as www.baidu.com Com will be sent to DNS (domain name resolver) and then the Ip address will be resolved * * *The same is true when we write the domain name and IP address in hosts. If you enter this domain name, it points to a fixed IP address * * 5. Local loop address: 127.0.0.1 corresponds to localhost * * 6. How to instantiate InetAddress: two methods: getByName(String host) and getLocalHost () * * 7. The port number identifies the process (program) running on the computer *Different processes have different port numbers *It is specified as a 16 bit integer 0 ~ 65535 *Port number classification: *Recognized port number: 0 ~ 1023 http-80 FTP-21 Telnet-23 *The registration port number: 1024 ~ 49151 is assigned to user processes or applications, such as Tomcat-8080 mysql-3306 oracle-1521 *Dynamic / private port number: 49152 ~ 65535 *The combination of port number and Ip address leads to a network Socket: the core of Socket network programming
1.InetAdress instantiation:
public class InetAddressTest { public static void main(String[] args){ try { InetAddress inet1=InetAddress.getByName("192.168.10.14"); System.out.println(inet1); InetAddress inet2=InetAddress.getByName("www.bilibili.com"); System.out.println(inet2); InetAddress inet3=InetAddress.getByName("127.0.0.1"); System.out.println(inet3); InetAddress inet4=InetAddress.getLocalHost(); System.out.println(inet4); //getHostName() System.out.println(inet2.getHostName()); //getHostAddress System.out.println(inet2.getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } } }
2.TCP network programming:
*TCP protocol: *Before using TCP protocol, a TCP connection must be established to form a data transmission channel *Before transmission, the "three-time handshake" mode is adopted for point-to-point communication, which is reliable *Two application processes of TCP protocol communication: client and server *A large amount of data transmission can be carried out in the connection *After transmission, the established connection needs to be released, which is inefficient (four waves) *For example: call
//Realize network programming of TCP //Example 1: the client sends information to the server, which displays the data on the console
//client @Test public void client(){ Socket socket= null; OutputStream os = null; try { //Create a Socket object to indicate the IP and port number of the server InetAddress inet=InetAddress.getByName("127.0.0.1"); socket = new Socket(inet,8899); //Gets an input stream for outputting data os = socket.getOutputStream(); //Operation of writing data os.write("Hello, I'm the client of this machine".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if(os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void server(){ Socket socket= null; InputStream is = null; ByteArrayOutputStream baos=null; try { //1. Create a ServerSocket on the server side and indicate its own port number ServerSocket ss=new ServerSocket(8899); //2. Call accept() to receive the socket from the client socket = ss.accept(); //3. Get input stream is = socket.getInputStream(); //There may be garbled code // byte[] cbuf=new byte[1024]; // int len; // while((len=is.read(cbuf))!=-1){ // String str=new String(cbuf,0,len); // System.out.println(str); // } //4. Read the data in the input stream baos=new ByteArrayOutputStream(); byte[] buffer=new byte[5]; int len; while((len=is.read(buffer))!=-1){ baos.write(buffer,0,len); } System.out.println(baos.toString()); System.out.println("Received from:"+socket.getInetAddress().getHostAddress()+"Data"); } catch (IOException e) { e.printStackTrace(); } finally { //5. Close resources if(baos!=null){ try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } if(is!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Example: save a photo to the client and send it back to the local server
@Test public void client(){ Socket socket= null; OutputStream os = null; FileInputStream fis= null; InputStream is = null; ByteArrayOutputStream baos= null; try { //1. Specify the ip address InetAddress inet=InetAddress.getByName("127.0.0.1"); //2. Provide ip and port number to determine a socket socket = new Socket(inet,8890); //3. Obtain the input stream for outputting data os = socket.getOutputStream(); //4. File object instantiation File file=new File("Xiang Hanzhi.jpg"); //5. Instantiation of flow fis = new FileInputStream(file); //6. Transfer data in byte[] cbuf=new byte[1024]; int len; while((len=fis.read(cbuf))!=-1){ os.write(cbuf,0,len); } //Turn off the data output and tell the server that my picture has been transmitted to avoid the server waiting all the time socket.shutdownOutput(); //Receive data from the server and display it on the console //1. Obtain the output stream for receiving data is = socket.getInputStream(); //Because the string to be transmitted at this time (Chinese takes up three bytes) may be garbled if ByteArrayOutputStream is not used //ByteArrayOutputStream is used to store some written characters in the array and output them together after reading them completely. In this way, it will not cause garbled code baos = new ByteArrayOutputStream(); //Data reading and writing operation byte[] cbuf1=new byte[5]; int len1; while((len1=is.read(cbuf1))!=-1){ baos.write(cbuf1,0,len1); } System.out.println(baos); } catch (IOException e) { e.printStackTrace(); } finally { if(baos!=null){ try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } if(is!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(fis!=null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if(os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void server(){ ServerSocket ss= null; Socket socket = null; InputStream is = null; FileOutputStream fos= null; OutputStream os = null; try { //Indicates the port number of the service ss = new ServerSocket(8890); //Receive socket from specified port number socket = ss.accept(); //Gets the input stream used to receive data is = socket.getInputStream(); //Instantiate file object File file=new File("Xiang Hanzhi 9.jpg"); //Instantiate flow object fos = new FileOutputStream(file); //Data reading and writing operation byte[] cbuf=new byte[1024]; int len; while((len=is.read(cbuf))!=-1){ fos.write(cbuf,0,len); } System.out.println("Picture transfer complete"); os = socket.getOutputStream(); os.write("I have received the picture of Xiang Han".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { if(os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if(fos!=null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(is!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if(ss!=null){ try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } }
3.UDP network programming:
*UDP protocol *Encapsulate the datagram, source and destination into packets without establishing a connection *The size of each datagram is limited to 64K *Whether the sending party is ready or not, the receiving party does not confirm the receipt, so it is an unreliable connection *Can broadcast and send *At the end of sending data, there is no need to release resources, low overhead and high speed *For example, watch online videos, send text messages, send telegrams and send missiles
Examples of UDP network programming:
@Test public void sender(){ DatagramSocket socket= null; try { socket = new DatagramSocket(); String str="I am UDP Missile sent by"; byte[] data=str.getBytes(); InetAddress inet=InetAddress.getLocalHost(); DatagramPacket packet=new DatagramPacket(data,0,data.length,inet,9090); socket.send(packet); } catch (IOException e) { e.printStackTrace(); } finally { if(socket!=null){ socket.close(); } } } @Test public void receiver(){ DatagramSocket socket= null; try { socket = new DatagramSocket(9090); byte[] buffer=new byte[100]; DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length); socket.receive(packet); System.out.println(new String(packet.getData(),0,packet.getLength())); } catch (IOException e) { e.printStackTrace(); } finally { if(socket!=null){ socket.close(); } } }
4.URL network programming:
* 1.URL: uniform resource locator, corresponding to a resource address on the Internet * 2. Format: * https://www.bilibili.com/video/BV1Qb411g7cz?p=627&spm_id_from=pageDriver *Protocol domain name (host name plus port number) resource address parameter list
Common methods:
public class URLTest { public static void main(String[] args) { try { URL url=new URL("https://www.bilibili.com/video/BV1Qb411g7cz?p=627&spm_id_from=pageDriver"); /* public String getProtocol() Gets the protocol name of the host public String getHost() Gets the host name of the URL public String getPort() Gets the port number of the URL public String getPath() Gets the file path of the URL public String getFile() Gets the file name of the URL public String getQuery() Gets the query name of the URL */ //public String getProtocol() gets the protocol name of the host System.out.println(url.getProtocol()); //public String getHost() gets the host name of the URL System.out.println(url.getHost()); //public String getPort() gets the port number of the URL System.out.println(url.getPort()); //public String getPath() gets the file path of the URL System.out.println(url.getPath()); //public String getFile() gets the file name of the URL System.out.println(url.getFile()); //public String getQuery() gets the query name of the URL System.out.println(url.getQuery()); } catch (MalformedURLException e) { e.printStackTrace(); } } }
URL programming case 1:
public class URLTest1 { public static void main(String[] args){ HttpURLConnection urlConnection = null; InputStream is = null; FileOutputStream fos= null; try { URL url=new URL("http://img.jutoula.com/201912/24/133207973.jpg"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); is = urlConnection.getInputStream(); fos = new FileOutputStream("Xiang Hanzhi.jpg"); byte[] cbuf=new byte[1024]; int len; while((len=is.read(cbuf))!=-1){ fos.write(cbuf,0,len); } System.out.println("Download complete"); } catch (IOException e) { e.printStackTrace(); } finally { if(fos!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(is!=null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(urlConnection!=null){ urlConnection.disconnect(); } } } }