1, Network communication protocol
1. Concept:
Through computer network, multiple computers can be connected. Computers in the same network need to abide by certain rules when connecting and communicating. In computer network, these rules of connection and communication are called network communication protocol. It has unified regulations on data transmission format, transmission rate, transmission steps, etc. both sides of communication must abide by them at the same time To complete the data exchange.
There are many kinds of network communication protocols. At present, the most widely used one is TCP/IP (Transmission Control Protocol / Internet Protocol), which includes TCP protocol and IP protocol, UDP (User Datagram Protocol) and other protocol groups. Before learning specific protocols, first understand the hierarchy of TCP/IP protocol groups.
2. Hierarchy of TCP / IP protocol:
Link layer: the link layer is used to define the physical transmission channel, usually the driver protocol for some network connection devices, such as the driver provided for optical fiber and network cable. Hardware
Network layer: network layer is the core of the whole TCP/IP protocol. It is mainly used to group the transmitted data and send the packet data to the target computer or network.
Transmission layer: it mainly enables the network program to communicate. In the network communication, the TCP protocol or UDP protocol can be used.
Application layer: mainly responsible for application protocol, such as HTTP protocol, FTP protocol, etc.
3.IP address and port number
In the TCP/IP protocol, the identification number is the IP address, which can uniquely identify a computer. At present, the version widely used for IP address is IPv4, which is represented by a binary number of four bytes. Because the IP address represented in binary form is very inconvenient to remember and process, the IP address is usually written in decimal form. Each byte uses a decimal number (0-255 )Indicates that the numbers are separated by the symbol ".", such as "192.168.1.100".
The IP address allows you to connect to the specified computer, but if you want to access an application in the target computer, you need to specify a port number as well. In a computer, different applications are distinguished by port numbers. The port number is represented by two bytes (16 bit binary number), and its value range is 0-65535. Among them, the port number between 0-1023 has been used in some well-known network services and applications. The user's ordinary application needs to use more than 1024 port numbers to avoid the port number being occupied by another application or service.
4.InetAddress class: IP address class
This class is used to encapsulate an IP address and provides a series of methods related to IP address. The following table lists some common methods of InetAddress class.
package com.oracle.Demo01; import java.net.InetAddress; import java.net.UnknownHostException; public class Demo01 { public static void main(String[] args) throws UnknownHostException { //Get object of local host InetAddress inet=InetAddress.getLocalHost(); System.out.println(inet); // // String [] str=inet.toString().split("/"); // System.out.println(str[0]); // System.out.println(str[1]); //Get local IP address System.out.println(inet.getHostAddress()); //Get local host name System.out.println(inet.getHostName()); //According to the target host name, get the InetAddress Object that contains the host name and IP address InetAddress in=InetAddress.getByName("LAPTOP-42J1FCTO"); System.out.println(in); } }
2, UDP and TCP protocol
UDP protocol:
UPD protocol is a connectionless communication protocol, that is, when data is transmitted, there is no logical connection between the sender and the receiver. That is to say, when sending data, the sender will not determine whether there is a receiver, and the receiver will not feed back information to the transmitter when receiving data.
Because UDP protocol consumes less resources and has high communication efficiency, it is usually used for the transmission of audio, video and ordinary data. For example, radio, video conference, television signal. Even if one or two packets are lost during the transmission, the transmission result will not be affected.
However, due to the undirected transmission of UDP protocol, the integrity of data can not be guaranteed. So it can't be used to transmit important data.
Note: the UDP protocol is limited to 64kb.
Example:
TCP protocol:
TCP protocol is a connection oriented communication protocol, that is, before transmitting data, it establishes logical connection between the sender and the receiver, and then transmits data. It provides reliable and error free data transmission between two computers. In the TCP connection, the client and the server must be specified. The client sends the connection request to the server. Each connection creation needs to go through "three handshakes". For the first handshake, the client sends a connection request to the server, waiting for the server to confirm. For the second handshake, the server sends a response back to the client, informing the client that it has received the connection request. For the third handshake, the client sends a confirmation message to the server again to confirm the connection. The whole interaction process is shown in the figure below.
Due to the connection oriented feature of TCP protocol, it can ensure the security of data transmission, so it is a widely used protocol. For example, when downloading files, if the data reception is incomplete, the file data will be lost and cannot be opened. Therefore, TCP protocol must be used when downloading files.
III. UDP communication
The construction method of datagram packet class:
Construction code of receiver: there is no specified IP address and port number, only used to receive packets.
The construction code of the transmitter: Specifies the byte array and data size of the encapsulated data, as well as the destination IP address (addr) and port number (port) of the data package
Common methods in datagram packet class:
package com.oracle.Demo01; import java.net.InetAddress; import java.net.UnknownHostException; public class Demo01 { public static void main(String[] args) throws UnknownHostException { //Get object of local host InetAddress inet=InetAddress.getLocalHost(); System.out.println(inet); // // String [] str=inet.toString().split("/"); // System.out.println(str[0]); // System.out.println(str[1]); //Get local IP address System.out.println(inet.getHostAddress()); //Get local host name System.out.println(inet.getHostName()); //According to the target host name, get the InetAddress Object that contains the host name and IP address InetAddress in=InetAddress.getByName("LAPTOP-42J1FCTO"); System.out.println(in); } }
The construction method of DatagramSocket class:
Transmitter: the system will automatically assign a port number that is not used by other applications
Receiver: must make a port number. In fact, it can also be used for the transmitter, but it also needs to set the port number.
Common methods of DatagramSocket class:
Transmitter:
package com.oracle.Demo01; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPSend { //Sender public static void main(String[] args) throws IOException { // 1.Create a packet object, encapsulate the data to be sent, and IP,Port of receiving end byte[] bytes="Hello".getBytes(); InetAddress inet=InetAddress.getLocalHost(); DatagramPacket dp=new DatagramPacket(bytes,bytes.length,inet,8000); //2.Create the terminal object and send the data package DatagramSocket ds=new DatagramSocket(); ds.send(dp); //3.close resource ds.close(); } }
Receiver:
package com.oracle.Demo01; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPRecieve { //receiving end public static void main(String[] args) throws IOException { //1.Create terminal, bind port number DatagramSocket ds=new DatagramSocket(8000); //2.Create byte array to receive data sent byte[] bytes=new byte[1024]; //3.Create package object DatagramPacket dp=new DatagramPacket(bytes, bytes.length); //4.receive data ds.receive(dp); //5.Unpacking int length=dp.getLength(); String ip=dp.getAddress().getHostAddress(); int port=dp.getPort(); System.out.println("ip Address:"+ip+" The port number is:"+port+"The content sent by the user of is"+new String(bytes,0,length)); //6.Release resources ds.close(); } }
IV. TCP communication
TCP communication is a strict distinction between the client and the server. When communicating, the client must first connect to the server to realize communication. The server cannot actively connect to the client, and the server program needs to be started in advance,
Wait for the client to connect.
In JDK, two classes are provided to implement TCP programs, one is ServerSocket, which is used to represent the server side, and the other is Socket, which is used to represent the client side.
1. ServerSocket class server side construction method:
2. ServerSocket class common methods:
3. Socket class client class
When using this construction method to create a Socket object, the server program running on the specified address and port will be connected according to the parameters. The parameter host receives an IP address of string type. (IP address and port number)
This method is similar to the second construction method in use. The parameter address is used to receive an InetAddress type object, which is used to encapsulate an IP address.
In the above Socket construction methods, the most commonly used one is the first one.
4. Common methods of Socket
In the common methods of Socket class, getInputStream() and getOutStream() are used to get input stream and output stream respectively. When the client and the server establish the connection, the data is interactive in the form of IO flow, so as to achieve communication.
Demo code:
client:
package com.oracle.Demo03; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; //client public class TCPClient { public static void main(String[] args) throws IOException { //Upload part // 1.Establish Socket Object, connecting to server Socket socket=new Socket("127.0.0.1",8000); //2.Through the client's socket object, Socket Method to get the byte output stream and write the data to the server OutputStream out=socket.getOutputStream(); //3.Write data out.write("how are you".getBytes()); //Receive replies from server InputStream in=socket.getInputStream(); byte[] bytes=new byte[1024]; int len=in.read(bytes); //Get local address String ip=socket.getInetAddress().getHostAddress(); System.out.println("client ip by"+ip+"Replies received are:"+new String(bytes,0,len)); //Release resources socket.close(); } }
Server side:
package com.oracle.Demo03; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { //Server side public static void main(String[] args) throws IOException { //Client received //1.Create server,Binding port number ServerSocket service=new ServerSocket(8000); //2.Calling the accept Method, establish connection, get socket object Socket socket=service.accept(); //3.use Socket Get input stream InputStream in=socket.getInputStream(); //4.Read data byte[] bytes=new byte[1024]; int len=in.read(bytes); String ip=socket.getInetAddress().getHostAddress(); System.out.println("Server side ip by"+ip+"Received data is:"+new String(bytes,0,len)); //Reply to client OutputStream out=socket.getOutputStream(); out.write("Received".getBytes()); //Release resources in.close(); out.close(); socket.close(); service.close(); } }
Exercise: upload files to the server:
Server side:
package com.oracle.Demo04; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Random; public class TCPServer { //Server side public static void main(String[] args) throws IOException { //1.Create server socket, bind port ServerSocket server=new ServerSocket(8000); //2.Receive socket object Socket socket=server.accept(); //3.Get input stream InputStream in=socket.getInputStream(); //4.Get folder(Create if not) File upload=new File("d:\\upload"); if(!upload.exists()){ //If not, create it. If not, do not execute this step upload.mkdirs(); } //5.Create a file output stream //Prevent duplication and cover when transferring large amount of data String filename="oracle"+System.currentTimeMillis()+ new Random().nextInt(999999)+".png"; //File.separator Separator, equal to“\\" FileOutputStream fos=new FileOutputStream(upload+File.separator+filename); //6.Write data byte[] bytes=new byte[1024]; int len=0; while((len=in.read(bytes))!=-1){ fos.write(bytes,0,len); } //Server reply upload succeeded OutputStream out=socket.getOutputStream(); out.write("Upload succeeded".getBytes()); //Release resources fos.close(); socket.close(); server.close(); } }
Client:
package com.oracle.Demo04; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; //Client transfers files to server public class TCPClient { //Client side public static void main(String[] args) throws IOException { // 1.Establish Socket Object, connecting to server Socket socket=new Socket("192.168.1.136",8888); //2.Get output stream through socket OutputStream out=socket.getOutputStream(); //3.Get data source FileInputStream fis=new FileInputStream("e:\\java\\outint.png"); //4.Read data int len=0; byte[] bytes=new byte[1024]; while((len=fis.read(bytes))!=-1){ //Write destination out.write(bytes,0,len); } //Put at the end of the stream to prompt the server for the end of the transfer statement socket.shutdownOutput(); //Receive replies from server: InputStream in=socket.getInputStream(); len=in.read(bytes); System.out.println(new String(bytes,0,len)); //Release resources fis.close(); socket.close(); } }