Stage 6 Network Programming
Each computer is connected through a network to achieve the effect of data interaction. The problem solved by network programming is how to make the program and program communicate and interact with each other.
Are you there?Are you a GG or MM?
(1) Overview of network models
(1) Two models
Network models generally refer to:
- OSI (Open System Interconnection Open System Interconnection) Reference Model
- TCP/IP Reference Model
(2) Overview of seven layers of network model
-
Physical Layer: Defines the standards for physical devices, such as the type of interface for network cables, the type of interface for optical fibers, the transmission rates of various transmission media, etc.Its main function is to transfer bitstream (that is, converting 1, 0 to current strength for transmission, and converting to 1, 0 after reaching the destination, which is commonly referred to as digital-to-analog conversion and analog conversion).This layer of data is called bits.
-
Data Link Layer: Encapsulates and unpacks MAC addresses (the addresses of network cards) of data received primarily from the physical layer.This layer of data is often referred to as frames.The device that works in this layer is a switch, through which data is transmitted.
-
Network layer: mainly encapsulates and unpacks the IP address (example 192.168.0.1) of the data received from the lower layer.The devices that work on this layer are routers, and data in this layer is often called packets.
-
Transport Layer: Defines some protocols and port numbers for data transmission (WWW port 80, etc.), such as TCP (Transmission Control Protocol, Transmission Efficiency, High Reliability, Data Required for High Reliability and Large Data Volume), UDP (User Datagram Protocol, contrary to TCP characteristics, Low Reliability for Transport), data with a small amount of data, such as QQ WeChat data, is transmitted in this way.The main purpose is to segment and transmit the data received from the lower layer, and then reassemble it after reaching the destination address.This layer of data is often called a segment.
-
Session layer: Establish a data transmission channel through the transport layer (port number: transport port and receive port).Mainly initiate or accept session requests between your systems (devices need to know each other whether IP or MAC or hostname)
-
Representation layer: mainly to interpret the received data, encryption and decryption, compression and decompression (that is, to convert what the computer can recognize into something that people can recognize (such as pictures, sounds, etc.).
-
Application layer: Mainly some terminal applications, such as FTP (various file downloads), WEB (IE browsing), QQ and so on (it can be understood as what we can see on the computer screen. That is terminal applications).
(2) Three elements of network programming
(1) IP address
A: Overview of IP addresses: IP addresses are the unique identification of computers in the network**
We should have seen more or less the format xxx.xxx.xxx.xxx x of an IP address, which should be similar in general, but computers do not only recognize binary data, but it is clear that our IP address is not binary. What is the reason?
Let's take a random IP address as an example to see
IP: 192.168.1.100
Conversion: 11000000 10101000 00001 01100100
But if we need this IP address in the future, it can be a hassle to remember, so for convenience, we convert the data on each byte of the IP address to decimal, and then separate it with'.': "dot decimal"
Composition of B:IP Address: Network Number Segment + Host Number Segment
Class A: The first segment is the host segment with the network number plus the last three segments, and one network number: 256256256 = 16777216
Class B: The first two segments are the network number segment + the last two host segments, and one network number: 256*256 = 65536
Class C: The first three segments are the network number segment + the host number segment of the last segment, and one network number is 256.
Classification of C:IP Addresses
Class A
1.0.0.1---127.255.255.254 (1)10.X.X.X is a private address (a private address is one that is not used on the Internet and is used in a local area network) (2)127.X.X.X is a reserved address for circular testing
Class B
128.0.0.1---191.255.255.254 172.16.0.0 - 172.31.255.255 is a private address 169.254.X.X is a reserved address
Class C
192.0.0.1 - 223.255.255.254 192.168.X.X is a private address
Class D
224.0.0.1---239.255.255.254
Class E
240.0.0.1---247.255.255.254
Two DOS commands
ipconfig view native ip address
ping is followed by ip address to test whether there is a problem communicating between this machine and the specified ip address
Special IP Address
127.0.0.1 loopback address (local)//that is, the ping local IP address is equivalent to ping 127.0.0.1
x.x.x.255 Broadcast Address
x.x.x.0 network address
Membership method of InetAddress
//Obtain an IP address object based on the string representation of the host name or IP address public static InetAddress getByName(String host):
import java.net.InetAddress; import java.net.UnknownHostException; public class InetAddressDemo { public static void main(String[] args) throws UnknownHostException { InetAddress address = InetAddress.getByName("192.168.24.1"); //Get two things: host name, IP address String name = address.getHostName(); String ip = address.getHostAddress(); System.out.println(name + "---" + ip); } } //Run Results LAPTOP-5T03DV1G---192.168.24.1
(2) Port
-
Physical Port Network Card
-
Logical Port What we mean is Logical Port
-
Each network program will have at least one logical port
-
Logical address used to identify processes, identification of different processes
-
Valid ports: 0~65535, where 0~1024 systems use or retain ports.
-
(3) Agreement
TCP: Transmission control protocol, low transmission efficiency, high reliability, for transmission of high reliability requirements, large amount of data
UDP: User datagram protocol, contrary to TCP, is used to transmit data with low reliability and small amount of data, such as QQ WeChat data, which is transmitted in this way
Summary:
TCP: Unlimited, inefficient and reliable data channel
UDP: Data packaging, limited, disconnected, efficient, unreliable
(3) Console simple chat cases
(1) UDP version V1.0
import java.io.IOException; import java.net.*; /* UDP Protocol send data: * A:Create Sender Socket Object * B:Create data and package it * C:Invoke send method of Socket object to send data package * D:Release Resources */ public class SendDemo { public static void main(String[] args) throws IOException { //Create socket object DatagramSocket ds = new DatagramSocket(); //Create data and package it //DatagramPacket(byte[] buf, int length, InetAddress address, int port) byte[] bys = "Hello,BWH!".getBytes();//Converts a string to an array of characters int length = bys.length; InetAddress address = InetAddress.getByName("192.168.24.1"); int port = 10086; //draft by oneself DatagramPacket dp = new DatagramPacket(bys, length, address, port); //Call the method of the Socket object to send a packet //public void send(DatagramPacket p) ds.send(dp); //Release Resources ds.close(); //The underlying layer relies on IO streams, so release resources } }
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; /* * UDP Protocol Receive Data: * A:Create Receiver Socket Object * B:Create a packet (receive container) * C:Call the receive method of the Socket object to receive data * D:Parse the package and display it in the console * E:Release Resources */ public class ReceiveDemo { public static void main(String[] args) throws IOException { // Create Receiver Socket Object // DatagramSocket(int port) DatagramSocket ds = new DatagramSocket(10086); // Create a packet (receive container) // DatagramPacket(byte[] buf, int length) byte[] bys = new byte[1024]; int length = bys.length; DatagramPacket dp = new DatagramPacket(bys, length); // Call the receive method of the Socket object to receive data // public void receive(DatagramPacket p) ds.receive(dp); // Parse the package and display it in the console // Get ip from the other party // public InetAddress getAddress() InetAddress address = dp.getAddress(); String ip = address.getHostAddress(); // public byte[] getData(): Get the data buffer // public int getLength(): Get the actual length of the data byte[] bys2 = dp.getData(); int len = dp.getLength(); String s = new String(bys2, 0, len); System.out.println(ip + ": " + s); // Release Resources ds.close(); } }
(2) UDP version V2.0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class SendDemo { public static void main(String[] args) throws IOException { //Create Socket Object on Sender DatagramSocket ds = new DatagramSocket(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = null; while ((line = br.readLine()) != null) { if ("886".equals(line)) { break; } //Create data and package byte[] bys = line.getBytes(); DatagramPacket dp = new DatagramPacket(bys, bys.length, InetAddress.getByName("192.168.24.1"), 10086); //send data ds.send(dp); } //Release Resources ds.close(); } }
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class ReceiveDemo { public static void main(String[] args) throws IOException { //Create Socket Object on Receiver Side DatagramSocket ds = new DatagramSocket(10086); while (true) { //Create a package byte[] bys = new byte[1024]; DatagramPacket dp = new DatagramPacket(bys, bys.length); //receive data ds.receive(dp); //Parse data String ip = dp.getAddress().getHostAddress(); String s = new String(dp.getData(), 0, dp.getLength()); System.out.println(ip + ": " + s); } // Release resources, but the recipient is that the server should always be on //ds.close(); } }
(3) UDP version V3.0
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class SendThread implements Runnable { private DatagramSocket ds; public SendThread(DatagramSocket ds) { this.ds = ds; } @Override public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = null; while ((line = br.readLine()) != null) { if ("886".equals(line)) { break; } // Create data and package byte[] bys = line.getBytes(); DatagramPacket dp = new DatagramPacket(bys, bys.length, InetAddress.getByName("192.168.24.1"), 10086); // send data ds.send(dp); } // Release Resources ds.close(); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; public class ReceiveThread implements Runnable { private DatagramSocket ds; public ReceiveThread(DatagramSocket ds) { this.ds = ds; } @Override public void run() { try { while (true) { //Create a package byte[] bys = new byte[1024]; DatagramPacket dp = new DatagramPacket(bys, bys.length); //receive data ds.receive(dp); //Parse data String ip = dp.getAddress().getHostAddress(); String s = new String(dp.getData(), 0, dp.getLength()); System.out.println("from " + ip + " data is : " + s); } } catch (IOException e) { e.printStackTrace(); } } }
import java.net.DatagramSocket; import java.net.SocketException; public class ChatRoom { public static void main(String[] args) throws SocketException { DatagramSocket dsSend = new DatagramSocket(); DatagramSocket dsReceive = new DatagramSocket(10086); SendThread st = new SendThread(dsSend); ReceiveThread rt = new ReceiveThread(dsReceive); Thread t1 = new Thread(st); Thread t2 = new Thread(rt); t1.start(); t2.start(); } }
(4) TCP version
package cn.bwh_06_TCP2; import java.io.*; import java.net.Socket; public class Clietn { public static void main(String[] args) throws IOException { Socket s = new Socket("192.168.24.1", 22222); //Keyboard entry object BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Package the streams in the channel BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); String line = null; while ((line = br.readLine()) != null) { if ("886".equals(line)) { break; } bw.write(line); bw.newLine(); bw.flush(); } s.close(); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(22222); Socket s = ss.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } s.close(); } }
(3) Other functions
(1) Client keyboard entry server writes to text file
//Encapsulate data in a channel BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); //Encapsulate Text File BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
(2) Client reads text file server console output
//Encapsulate Text File BufferedReader br = new BufferedReader(new FileReader("Demo.java")); //Encapsulate data in a channel BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); String line = null; while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); bw.flush(); }
Ending:
If there are any inadequacies or errors in the content, you are welcome to leave a message for me, Crab and Crab!^^
If you can help, pay attention to me!(The series will be updated at the first time on Public Number)
We don't know each other here, but we are working hard for our dreams.
A public slogan insisting on the original Java technology: more than 20 years