1, Network protocol layering idea
What is the idea of network protocol layering? The conceptual nature of the system is not mentioned. For example, if a general wants to convey an order to a soldier, the general needs to convey the order first from the school officer rank, then from the school officer rank to the lieutenant rank, and so on, and finally to the soldier.
Layered management of TCP/IP
The most important point in TCP/IP protocol is layering. TCP/IP protocol family is divided into application layer, transmission layer, network layer, data link layer and physical layer. Of course, there are also four or seven layers according to different models.
-
physical layer
This layer is responsible for the transmission of bit stream between nodes, that is, physical transmission. The protocol of this layer is related to both link and transmission medium. Generally speaking, it is a physical means to connect computers.
-
data link layer
The main function of controlling the communication between the network layer and the physical layer is to ensure reliable data transmission on the physical line. In order to ensure transmission, the data received from the network layer is divided into specific frames that can be transmitted by the physical layer. Frame is a structural packet used to move data structure. It contains not only the original data, but also the physical addresses of the sender and receiver, as well as error correction and control information. The address determines where the frame will be sent, and the error correction and control information ensures that the frame arrives without error. If the receiving point detects an error in the transmitted data when transmitting the data, it will notify the sender to resend the frame.
-
network layer
Decide how to route data from the sender to the receiver. The network layer determines the best way from node A to node B in the network by comprehensively considering the transmission priority, the degree of network congestion, the quality of service and the cost of optional routing. That is, establish host to host communication.
-
Transport layer
This layer provides end-to-end communication for applications on two hosts. The transport layer has two transmission protocols: TCP (transmission control protocol) and udp (User Datagram Protocol). Among them, TCP is a reliable connection oriented protocol, and udp is an unreliable or connectionless protocol
-
application layer
After the application receives the data from the transport layer, it needs to interpret it. The format of interpretation must be specified in advance, and the application layer is to specify the data format of the application. The main protocols are: http FTP, telent, etc
Layered thought
1. Each layer is independent of each other, and each layer has corresponding interfaces to link the upper and lower layers
2. If any layer changes, as long as the interface relationship between layers remains unchanged, the upper and lower layers of this layer will not be affected
3. If the whole system is divided into several relatively independent subsystems, i.e. layered idea, each layer can be debugged separately during debugging and maintenance, and the whole system will not be paralyzed due to a certain layer
2, IP
IP address is used to mark the address of each computer in TCP/IP communication protocol. It is usually expressed in decimal system, such as 192.168.1.100. But inside the computer, the IP address is a 32-bit binary value, such as 11000000 10101000 00000001 00000110 (192.168.1.6).
The IP address on each computer is unique. Different applications on each computer can be divided into different ports, and the ports can be divided into TCP and UDP, each with 65536 (i.e. 2 ^ 16)
3, TCP and UDP
1. TCP/UDP are both transport layer protocols, but they have different special effects and different application scenarios.
2. TCP's third handshake
- First handshake: A calls B and says, can you hear me?
- The second handshake: B receives A's message and says to A: I can hear you. Can you hear me?
- The third Handshake: A received B's message and said yes. I'll send you A message!
After three handshakes, both A and B can be sure of one thing: you can hear what I say; I can hear what you say. In this way, normal communication can be started. If it is twice, it will not be determined.
3. TCP and UDP program and writing method
(1)TCP:
ServerSocket side
1. Establish ServerSocket server port
2. Call the accept() method in the ServerSocket class and wait for the reception
3. Establish InputStream input and OutputStream output channels
4. Encapsulate byte data into DataInputStream and DataOutputStream
5. Call readUTF() method in DataInputStream class to read data, and writeUTF() method in DataOutputStream class to write data
6. Close the flow channel
The code is as follows:
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TestSockServer { public static void main(String[] args) { InputStream in=null; OutputStream out=null; try { //1. Establish ServerSocket server port ServerSocket ss=new ServerSocket(7777); //2. Call the accept() method in the ServerSocket class and wait for the reception Socket socket=ss.accept(); // 3. Establish InputStream input and OutputStream output channels in=socket.getInputStream(); out=socket.getOutputStream(); //4. Encapsulate byte data into DataInputStream and DataOutputStream DataInputStream dis=new DataInputStream(in); DataOutputStream dos=new DataOutputStream(out); //5. Then call the readUTF() method in the DataInputStream class to read the data, and writeUTF() in the DataOutputStream class to write the data String s=null; if((s=dis.readUTF())!=null){ System.out.println(s); System.out.println("from:"+socket.getInetAddress()); System.out.println("Port:"+socket.getPort()); } dos.writeUTF("hi,hello"); //6. Close flow channel dos.close(); dis.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
Clinet end
1. Establish socket port and IP address. Note that Clint has more IP addresses than Server
2. Establish input and output flow channels
3. Encapsulate byte data into DataInputStream and DataOutputStream
4. Call the readUTF() method in the DataInputStream class to read data, and writeUTF() in the DataOutputStream class to write data
5. Close the flow channel
The code is as follows:
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class TestSockClinet { public static void main(String[] args) throws IOException { InputStream is=null; OutputStream os=null; try { //1. Establish socket port and IP address. Note that Clint has more IP addresses than Server Socket socket=new Socket("localhost",7777); //2. Establish input and output flow channels is=socket.getInputStream(); os=socket.getOutputStream(); //3. Encapsulate byte data into DataInputStream and DataOutputStream DataInputStream dis=new DataInputStream(is); DataOutputStream dos=new DataOutputStream(os); //4. Call the readUTF() method in the DataInputStream class to read data, and writeUTF() in the DataOutputStream class to write data dos.writeUTF("hei"); String s=null; if((s=dis.readUTF())!=null); System.out.println(s); //5. Close flow channel dis.close(); dos.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } }
In TCP, the writing method of Server side and Client side is basically the same. The only difference is that there are multiple accept() methods on Server side and multiple IP addresses on Client side. Before starting program z, you must start Server side first and then Celient
The comprehensive exercises of TCP code dialog box are as follows:
Server side
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class TalkServer { public static void main(String[] args) throws IOException { Socket socket=null; ServerSocket ss=null; try { ss=new ServerSocket(4700);//Build server socket=ss.accept();//Establish server port connection } catch (Exception e) { System.out.println("can not listen to:"); System.out.println("Error"+e);//Error exception System.exit(0);//sign out } //1) Establish socket input channel and input the conversation BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream())); //2) Display Cline end System.out.println("Cline:"+is.readLine()); //3) Establish socket output channel to transmit the conversation PrintWriter pw=new PrintWriter(socket.getOutputStream()); //BufferedWriter bw=new BufferedWriter(new OutStreamReader(socket.getOutStream())); //4) Convert keyboard input into character input stream BufferedReader sin=new BufferedReader(new InputStreamReader(System.in)); String s;//null s=sin.readLine();//Read one line //5) Display dialog box while(!s.equals("bye")){ //If the keyboard is not equal to bye is true, the keyboard input bye ends pw.println(s); //Transfer the string entered on the keyboard to the socket port pw.flush(); //buffer System.out.println("Server:"+s); System.out.println("Clinet:"+is.readLine()); } is.close(); socket.close(); ss.close(); } }
Client side
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class TalkClient { public static void main(String[] args) { try { //1) Establish socket port Socket socket=new Socket("127.0.0.1",4700); //2) Establish socket output channel to transmit the conversation PrintWriter pw=new PrintWriter(socket.getOutputStream()); //3) Establish socket input channel and input the conversation BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream())); //4) Convert keyboard input into character input stream BufferedReader sin=new BufferedReader(new InputStreamReader(System.in)); String s; s=sin.readLine(); //5) while(!s.equals("bye")){ pw.println(s); pw.flush(); System.out.println("Clinet:"+s); System.out.println("Server:"+is.readLine()); } pw.close(); is.close(); socket.close(); } catch (Exception e) { System.out.println("Error"+e); } } }
(2)UDP
Differences between UDP and TCP
1. UDP is different from TCP. The Server side and Client side of UDP have their own ports. The Client side must have the same interface with the Server side when contracting
2. UDP calls the receive () method to receive data through datagram packet class, and datagram socket calls the send () method to send data. Different from TCP establishing flow channel
3. TCP transmits input data through stream, and UDP transmits input data by wrapping basic data types into arrays
UDPServer end
1. Create a new array
2. Create a DatagramPacket class to store the array
3. Create UDP port 5678
4. Call the method receive() in DatagramSocket class to receive data packets
5. Convert the received data packet into an array
6. DataInputStream calls the readLong() method to read data
The code is as follows
import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class TestUDPServer2 { public static void main(String[] args) throws Exception { //1. New array byte b[]=new byte[1024]; //2. Create a new DatagramPacket class to store the array DatagramPacket dp=new DatagramPacket(b,b.length); //3. Create UDP port 5678 DatagramSocket ds=new DatagramSocket(5678); //4. Call the method receive() in the DatagramSocket class to receive the packet while(true){ ds.receive(dp);//Receive packets from this socket //5. Convert the received packets into an array ByteArrayInputStream bais=new ByteArrayInputStream(b); //6. DataInputStream calls the readLong() method to read data DataInputStream dis=new DataInputStream(bais); System.out.println(dis.readLong()); } } }
UDPClient end
1. Create a new long type attribute
2. Convert the sent data packet into an array
3. Store the array sending package in DataOutputStream data and write it to
4. Call bytearrayoutputstream The tobytearray () method is stored in an array
5. Call datagram packet Send() method sends packets
The code is as follows:
import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; public class TestUDPClinet2 { public static void main(String[] args)throws Exception{ //1. New long type attribute long n=10000L; //2. Convert the sent packet into an array ByteArrayOutputStream baos=new ByteArrayOutputStream(); //3. Store the array sending package in DataOutputStream data and write it to DataOutputStream dos=new DataOutputStream(baos); dos.writeLong(n); //4. Call bytearrayoutputstream The tobytearray () method is stored in an array byte [] buf=baos.toByteArray(); //5. Call datagram packet Send() method sends packets DatagramPacket dp=new DatagramPacket(buf, buf.length,new InetSocketAddress("127.0.0.1",5678));//dp port must be consistent with Server port DatagramSocket ds=new DatagramSocket(9999);//Cline port ds.send(dp);//Contract awarding ds.close(); } }