“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

First, network basic knowledge

The purpose of network programming is to communicate directly or indirectly with other computers through network protocols.

Computer networks are diverse in form and complex in content. Computers on a network must follow certain protocols to communicate with each other. The most widely used network protocol is TCP/IP, which is used on the Internet.

IP address: unique globally. IP addresses are logical addresses compared with the Internet.

IP address classification:

1. Class A addresses

The first byte of A class A address is the network address, and the other three bytes are the host address. In addition, the highest bit of the first byte is fixed at 0.

Class A addresses range from 1.0.0.1 to 126.155.255.254.

Private and reserved addresses in Class A addresses:

10.0.0.0 to 10.255.255.255 are private addresses (private addresses are those that are not used on the Internet but are used in the LOCAL area network).

127.0.0.0 to 127.255.255.255 are reserved addresses for cyclic testing.

2. Class B address

The first and second bytes of class B addresses are network addresses, and the other two bytes are host addresses. The first two bytes of the first byte are fixed to 10.

Class B addresses range from 128.0.0.1 to 191.255.255.254.

Private and reserved addresses for class B addresses

172.16.0.0 to 172.31.255.255 are private addresses

169.254.0.0 to 169.254.255.255 are reserved addresses. If your IP address is automatically obtained and you cannot find an available DHCP server on the network, you will get an IP address from 169.254.0.0 to 169.254.255.255.

3. Class C addresses

The first, second, and third bytes of class C addresses are network addresses, and the fourth byte is the host address. In addition, the first three bytes are fixed to 110.

Class C IP addresses range from 192.0.0.1 to 223.255.255.254.

Private address in class C address:

192.168.0.0 to 192.168.255.255 are private addresses.

4. Class D address

The first four bits of the first byte of a class D address, regardless of network address or host address, are fixed at 1110.

Class D addresses range from 224.0.0.1 to 239.255.255.254

Mac address: a unique Mac address for each NIC.

Ports: There are 65536 (2^16) ports in the OS, through which processes exchange data. You need to enter the IP address and port information when connecting the cable.

Computer communication is actually the process communication between hosts. The process communication needs to be connected in the port.

192.168.0.23:21

Protocol: Rules, standards, or conventions established for the exchange of data (communication) over a network.

The protocols at different layers are completely different.

Network layer: addressing, routing (the process of getting to an address)

Transport layer: Port connection

TCP model: application layer/transport layer/network layer/network interface

A port is an abstract software structure related to protocol: TCP23 port and UDT23 port are two different concepts.

Ports above 1024 should be used. The following ports have been configured.

TCP/IP model

Application

(FTP,HTTP,TELNET,POP3,SMPT)

Transport

(TCP,UDP)

Network

(IP,ICMP,ARP,RARP)

Link

(Device driver,… .).

Note:

IP: addressing and routing

Address Resolution Protocol (ARP) : Translates an IP Address into a Mac Address

Reflect Address Resolution Protocol (RARP) Indicates the reverse Address Resolution Protocol

Internet Control Message Protocol (ICMP) Checks link connections. Tools to use this protocol: ping, traceroute

Second, the TCP Socket

TCP, short for Tranfer Control Protocol, is a connection-oriented Protocol that ensures reliable transmission. Through TCP protocol transmission, the obtained is a sequential error-free data flow. A connection must be established between two pairs of sockets on the sender and receiver to communicate over TCP. When one socket (usually a server socket) is waiting for a connection to be established, the other socket can request a connection. Once the two sockets are connected, They can be two-way data transmission, both can send or receive operations.

1) The server allocates a port number. The server waits for the signal from the client using the Accept () method. Once the signal is received, the socket connection is opened and OutputStream and InputStream are obtained from the socket.

2) The client provides the host address and port number to establish a connection with the socket port to obtain OutputStream and InputStream.

TCP/IP transport layer protocol

1. Establish the TCP server

Steps to create a TCP server-side program:

1). Create a ServerSocket

2). Accept client connection requests from ServerSocket

3). Create a service thread to process the new connection

4). In the server thread, get the I/O stream from the socket

5). Read and write the I/O stream to complete the interaction with customers

6). Close the I/O stream

7). Close the Socket

ServerSocket server = new ServerSocket(post)

Socket connection = server.accept();

ObjectInputStream put=new ObjectInputStream(connection.getInputStream());

ObjectOutputStreamo put=newObjectOutputStream(connection.getOutputStream());  

Process input and output streams;

Close streams and sockets.

2. Establish the TCP client

Steps to create a TCP client program:

1). Create a Socket

2). Get the I/O flow

3). Perform read and write operations on I/O streams

4). Close the I/O stream

5) close the Socket

Socket connection = new Socket(127.0.0.1, 7777);

ObjectInputStream input=new ObjectInputStream(connection.getInputStream());

ObjectOutputStream utput=new ObjectOutputStream(connection.getOutputStream());
Copy the code

Process input and output streams;

Close streams and sockets.

3. Establish UDP connections

UDP is short for User Datagram Protocol. It is a connectionless Protocol. Each Datagram is an independent piece of information, including a complete source address or destination address. The arrival time and correctness of the contents cannot be guaranteed.

Comparison: TCP has a strong vitality in network communication, for example, remote connection (Telnet) and file transfer (FTP) require data of variable length to be reliably transmitted; Since there is TCP to ensure reliable transmission, why do we need UDP to ensure unreliable transmission? There are two main reasons. First, reliable transmission is to pay the price, the correctness of the data content of the test must occupy the processing time of the computer and the bandwidth of the network, so TCP transmission efficiency is not as high as UDP. Second, in many applications, there is no need to ensure strict transmission reliability, such as video conference system, audio and video data is not required to be absolutely correct, as long as the consistency can be guaranteed, in this case, the use of UDP will be more reasonable.

Such as: www.tarena.com.cn:80/teacher/zhu…

Protocol name :// Machine name + port number + file name

2. Common methods of URL classes

After a URL object is generated, its properties cannot be changed, but we can obtain these properties through the methods provided by the class URL:

Public String getProtocol() Gets the protocol name of the URL.

Public String getHost() gets the host name of the URL.

Public int getPort() gets the port number of the URL, or -1 if no port is set.

Public String getFile() gets the file name of the URL.

Public String getRef() gets the relative location of the URL in the file.

Public String getQuery() gets query information about this URL.

Public String getPath() Obtains the path of the URL

Public String getAuthority() obtains the permission information of the URL

Public String getUserInfo() gets user information

Public String getRef() gets the anchor of the URL

  1. For example, copy the front page of the Tarena website to this machine.
import java.net.*; import java.io.*; import java.util.*; public class TestURL{ public static void main(String[] arg){ System.out.println("http://www.tarena.com.cn:80/index.htm===>"); //System.out.println(getWebContent()); writeWebFile(getWebContent()); } public static String getWebContent(){ URL url = null; HttpURLConnection uc = null; BufferedReader br = null; final int buffLen = 2048; byte[] buff = new byte[buffLen]; String message = ""; String tmp = ""; int len = -1; String urlStr = "http://www.tarena.com.cn:80/index.htm"; try{ url = new URL(urlStr); System.out.println("before openConnection ====>"+new Date()); uc = (HttpURLConnection)url.openConnection(); System.out.println("end openConnection ====>"+new Date()); br = new BufferedReader( new InputStreamReader(uc.getInputStream())); System.out.println("end getINputStream() ====>"+new Date()); while( ( tmp = br.readLine())! =null){ message += tmp; } System.out.println("end set message ====>"+new Date()); }catch(Exception e){e.printStackTrace(); System.exit(1); } finally{ if(br! =null){ try{ br.close(); }catch(Exception ioe){ioe.printStackTrace(); } } } return message; } public static void writeWebFile(String content){ FileWriter fw = null; try{ fw = new FileWriter("index.htm"); fw.write(content,0,content.length()); }catch(Exception e){ e.printStackTrace(); }finally{ if(fw! =null){ try{ fw.close(); }catch(Exception e){} } } } }Copy the code

Fourth, the UDP socket

This way of information transmission is equivalent to fax, information packaging, at the receiving end prepared paper.

Features:

  1. Based on UDP connectionless protocol

  2. Reliable transmission of messages is not guaranteed

  3. They are supported by the DatagramSocket and DatagramPacket classes in Java technology

DatagramSocket (postman) : indicates the Socket concept corresponding to datagrams. You do not need to create two sockets and cannot use input and output streams.

DatagramPacket: A packet of data transmitted over UDP in a byte array that contains the destination address and port as well as the information to be transmitted (so no point-to-point connections are required).

DatagramPacket classification:

DatagramPacket(byte[] buf,int length) DatagramPacket(byte[] buf,int length)

                      DatagramPacket(byte[] buf,int offset,int length)

DatagramPacket(byte[] buf,int length, InetAddress,int port) DatagramPacket(byte[] buf,int Length, InetAddress,int port)

                      DatagramPacket(byte[] buf,int offset,int length,InetAddress address,int port)

Note: The InetAddress class is used to encapsulate IP addresses

No constructor, pass

InetAddress.getByAddress(byte[] addr):InetAddress

InetAddress.getByName(String host):InetAddress

And so on.

1. Establish the UDP sender

Procedure to create a UDP sender program:

1). Create a DatagramPacket containing the sent data and the IP address and port of the receiver

Number.

2). Create a DatagramSocket containing the IP address and port number of the sender.

3). Send data

4). Close the DatagramSocket

byte[] buf = new byte[1024]; DatagramSocket datagramSocket = new DatagramSocket(13); // set port DatagramPacket intputPacket = new DatagramPacket (buf,buf.length); datagramSocket.receive(inputPacket); DatagramPacket outputPacket = new DatagramPacket (buf,buf.length, inetAddress,port); datagramSocket.send(outputPacket);Copy the code

There is no stream established so there is no need to disconnect.

2. Establish the UDP receiving end

Procedure for creating a UDP receiver program:

1). Create a DatagramPacket to store the data sent by the sender as well as the IP address and port number of the sender.

2). Create a DatagramSocket that specifies the IP address and port number of the receiver.

3). Receiving data

4). Close the DatagramSocket

byte[] buf = new byte[1024]; DatagramSocket datagramSocket = new DatagramSocket(); DatagramPacket outputPacket=new DatagramPacket(Buf, buf.length, serverAddress, serverPort); DatagramPacket inputPacket=new DatagramPacket(buf, buf.length); datagramSocket.receive(inputPacket);Copy the code

URL class: can directly send or read data on the network.

Socket class: Can be thought of as a communication channel between two different host programs over a network.

Datagram class: This puts a record of the destination of the data in a packet and puts it directly on the network.

InetAddress class: A class used to store Internet addresses (IP addresses, domain names).