Basically, network applications are TCP (Transmission Control Protocol) and UDP (User datasync Protocol User Datagram Protocol). TCP is a connection-oriented communication Protocol, UDP is a connectionless communication protocol. 127.0.0.1 is the loop address used for testing. It is equivalent to the local address of localhost. It can be accessed without a NIC or DNS. the port address ranges from 0 ~ Between 65535, 0 ~ Ports between 1023 are used for some well-known network services and applications. Your common network applications should use ports above 1024. socket connects to the Socket. Java provides the corresponding classes for TCP and UDP respectively. TCP is java.net. serverSocket (for server) and java.net. socket (for the client); UDP is java.net. mongoramsocket.1: Java programming UDP network program 1.1. mongoramsocketmongoramsocket has the following constructor methods: 1. mongoramsocket (): constructs a datagram socket and binds it to any available port on the local host. 2. DatagramSocket (int port): Creates a datagram socket and binds it to the specified port on the local host. 3. DatagramSocket (int port, InetAddress laddr): Creates a datagram socket and binds it to the specified local address. That is, specify the NIC to send and receive data. if the IP address of the network adapter is not specified when the initramsocket object is created, the underlying driver automatically selects a network adapter to send the data. When receiving the data, all NICs receive the same data as the port. when sending information, you can choose not to specify the port number. When receiving information, you must specify the port number because you want to receive the specified data. use DatagramSocket to send data. send (DatagramPacket p) method. Use DatagramSocket to receive data. receive (DatagramPacket p) method. 1.2. The initrampacketdatagrampacket class has the following constructor methods: 1. DatagramPacket (byte [] buf, int length): constructs an initrampacket to receive data packets whose length is length. 2. mongorampacket (byte [] buf, int length, InetAddress address, int port): constructs a datagram packet to send a packet with length to the specified port number on the specified host. The first constructor is used to receive data, and the second constructor is used to send data. 1.3. Class for packaging IP addresses in InetAddressJava, DatagramPacket. getAddress () can be used to obtain the IP address of the sender or receiver. datagramPacket. getPort () can be used to obtain the port of the sender or receiver. 1.4. UDP program example Sender: [java] import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; public class UdpSend {public static void main (String [] args) throws Exception {DatagramSocket ds = new DatagramSocket (); String str = "hello, World! "; DatagramPacket dp = new DatagramPacket (str. getBytes (), str. length (), InetAddress. getByName ("192.168.0.105"), 3000); ds. send (dp); ds. close (); // close the connection} receiver: [java] import java.net. datagramPacket; import java.net. datagramSocket; public class UdpRecv {public static void main (String [] args) throws Exception {DatagramSocket ds = new DatagramSocket (3000); byte [] buf = new byte [1024]; datagramPacket dp = New DatagramPacket (buf, buf. length); ds. receive (dp); String str = new String (dp. getData (), 0, dp. getLength (); System. out. println (str); System. out. println ("IP:" + dp. getAddress (). getHostAddress () + ", PORT:" + dp. getPort (); ds. close () ;}} run the receiving program before running the sending program. if the receiving program does not receive data, it will be blocked until the program is closed after receiving the data. if no data is sent over the network and the receiving program is not blocked, A occupied port is usually used. 2. Write the TCP network program 2.1 in Java and the TCP network service program in ServerSocket. java.net is used first. serverSo The cket class is used to create a server Socket. Its common constructor is: 1. ServerSocket (int port): Creates a server Socket bound to a specific port. 2. ServerSocket (int port, int backlog): Create a server socket and bind it to the specified local port number by using the specified backlog (the number of customers waiting for the connection request to be kept when the server is busy. 3. ServerSocket (int port, int backlog, InetAddress bindAddr): Create a server using the specified port, listener backlog, and local IP address to bind. 2.2. to establish a connection between the Socket client and the server, you must first create a Socket object. Its common constructor methods include: 1, Socket (String host, int port ): create a stream socket and connect it to the specified port number on the specified host. 2. Socket (InetAddress address, int port): Creates a stream Socket and connects it to the specified port number of the specified IP address. 3. Socket (InetAddress address, int port, InetAddress localAddr, int localPort): Create a Socket and connect it to the specified remote address on the specified remote port. 4. Socket (String host, int port, InetAddress localAddr, int localPort): Create a Socket and connect it to the specified remote port on the specified remote host. For common applications, it is very simple and convenient to use the 1st constructor to create the Socket object of the client and establish a connection with the server. the server program calls ServerSocket. the accept method waits for the client's connection request. Once the accept receives the client's connection request, this method returns a Socket object that has established a leased line connection with the client, without the need for a program to create this Socket object. the two sockets with established connections exchange data in the form of IO streams. Java provides the Socket. getInputStream returns the input stream object of the Socket, Socket. getOutputStream returns the output stream object of the Socket. 2.3. TCP program example server program: [java] import java. io. inputStream; import java. io. outputStream; import java.net. serverSocket; import java.net. so Cket; public class TcpServer {public static void main (String [] args) throws Exception {ServerSocket ss = new ServerSocket (8000); Socket s = ss. accept (); InputStream ips = s. getInputStream (); OutputStream ops = s. getOutputStream (); ops. write ("hello, World! ". GetBytes (); byte [] buf = new byte [1024]; int len = ips. read (buf); System. out. println (new String (buf, 0, len); ips. close (); ops. close (); s. close (); ss. close () ;}} in this program, a ServerSocket object waiting for connection on port 8000 is created. After receiving a connection request from a customer, the program obtains the input and output stream object from the Socket object connected to this customer. The output stream first sends a string of characters to the client, and then reads the information sent by the client through the input stream, print the information and close all resources. you must first run the server program before running the client program. When the TCP server runs on the Socket. the accept method is blocked when the accpet () method waits for the client to connect. This method will not return until a client connection request arrives, If no request arrives and no congestion occurs, a occupied port is usually used. we can use the telnet tool provided by windows to test the server program in the command line window: The command is as follows: telnet localhost 8000 can be seen, telnet will be sent as long as there is input, therefore, if we want to read multiple characters at a time on the server side, we need to further process them. See the following code: [java] import java. io. bufferedReader; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java.net. serverSocket; import java.net. socket; public class TcpServer {public static void main (String [] Args) throws Exception {ServerSocket ss = new ServerSocket (8000); Socket s = ss. accept (); InputStream ips = s. getInputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (ips); // package InputStream to add cache OutputStream ops = s. getOutputStream (); ops. write ("hello, World! ". GetBytes (); System. out. println (br. readLine (); br. close (); // close the packaging class, which will automatically close the base class ops. close (); s. close (); ss. close () ;}} again using the telnet tool, you can see that more than one character can be sent this time, press the Enter key and then send data to the server. 2.4. Improved server program in the TCP program example: In most cases, the server must serve multiple clients, but one accept method call only receives one connection. Therefore, put the accept method in a loop statement to receive multiple connections. the data exchange code for each connection is also placed in a loop so that the two can exchange data continuously. the Data Exchange Code of each connection must be run in an independent thread. Otherwise, other program code cannot be executed during the code running, and the accept method cannot be called, new connections cannot enter. the following is an example. The client sends a string to the server. The server sorts all the characters in the string in reverse order and sends them back to the client. enter "quit" on the client to exit the program. [java] import java. io. bufferedReader; import java. io. dataOutputStream; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java.net. serverSocket; import java.net. socket; public class TcpServer {public static void main (String [] args) throws Exception {ServerSocket ss = new ServerSocket (8000); while (true) {Socket s = ss. accept (); new Thread (new Servicer (s )). start () ;}} class Servicer implements Runnable {Socket s; public Servicer (Socket s) {this. s = s;} public void run () {try {InputStream ips = s. getInputStream (); OutputStream ops = s. getOutputStream (); BufferedReader br = new BufferedReader (new InputStreamReader (ips); DataOutputStream dos = new DataOutputStream (ops); while (true) {String strWord = br. readLine (); if (strWord. repeated signorecase ("quit") {break;} String strEcho = (new StringBuffer (strWord ). reverse (). toString (); dos. writeBytes (strWord + "------->" + strEcho + System. getProperty ("line. separator ");} br. close (); dos. close (); s. close ();} catch (Exception e) {e. printStackTrace () ;}} 2.5, TCP program example client program: [java] import java. io. bufferedReader; import java. io. dataOutputStream; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java.net. inetAddress; import java.net. socket; public class TcpClient {public static void main (String [] args) throws Exception {if (args. length <2) {System. out. println ("Usage: java TcpClient ServerIP ServerPort"); return;} Socket s = new Socket (InetAddress. getByName (args [0]), Integer. parseInt (args [1]); InputStream ips = s. getInputStream (); OutputStream ops = s. getOutputStream (); BufferedReader brKey = new BufferedReader (new InputStreamReader (System. in); DataOutputStream dos = new DataOutputStream (ops); BufferedReader brNet = new BufferedReader (new InputStreamReader (ips); while (true) {String strWord = brKey. readLine (); dos. writeBytes (strWord + System. getProperty ("line. separator "); if (" quit ". equalsIgnoreCase (strWord) {break;} else {System. out. println (brNet. readLine () ;}} dos. close (); brNet. close (); brKey. close (); s. close () ;}run the server program first, and then use java TcpClient 192.168.0.3 8000 on the command line to start the client program. we can start multiple client programs. we can use the netstat tool to view the used Port