Java network communication
- Because the data link layer programming and communication are closely related to the device, the network layer programming is closely related to the operating system. Java network programming starts from the transport layer and is divided into high-level network programming (based on the application layer) and low-level network programming (based on the transport layer) according to the level of programming protocol.
- Use high-level network programming based on URL and low-level network programming based on transport layer.
Network communication protocol
- Physical Layer: transmission data frame on local LAN, which is responsible for managing the interworking between computer communication equipment and network media, and realizing the information transmission in bit form between interconnected equipment through physical electrical interface
- Data Link Layer: it is responsible for network addressing, error detection and error correction. It is the data channel for binary information transmission between adjacent node devices of the network, and is responsible for the establishment and removal of the data channel.
- Network Layer: it determines the path selection and forwarding of data, adds the network header (NH) to the data packet to form a packet, and solves the communication problems across multiple links and even between different network devices. It is an end-to-end communication
- Transport Layer: add the transport header (TH) to the data to form data packets, solve the communication transmission and communication management between different network devices, decompose the data information to be communicated in the upper layer into standard data units, and reorder and integrate these data units after they arrive at the terminal.
- Session Layer: it is responsible for setting and maintaining the communication connection between two computers in the computer network during data transmission, establishing the connection according to the characteristics and laws for user interaction information, and providing session address and session management services
- Presentation Layer: convert the data obtained from the session layer into an expression that can be understood by the application layer, or convert several application layer data into a form that can be transmitted by the session layer
- Application Layer: provides an interface for application software to set up communication with another application software
TCP and UDP
-
TCP and UDP are both transport layer protocols
-
TCP (Transmission Control Protocol) - Transmission Control Protocol
-
UDP (User Data Protocol) -- User Datagram Protocol
TCP | UDP | |
---|---|---|
Transmission data reliability | TCP is a reliable protocol, which can ensure that the receiver can completely and correctly obtain all the data sent by the sender. | UDP is an unreliable protocol. The datagrams sent by the sender do not necessarily arrive at the receiver in the same order, and there is no guarantee that the receiver will receive them. |
Communication mode | A connection must be established before data transmission, and the sender and receiver transmit data on the connection. | The sender and receiver have not established a connection, and complete address information is given in each datagram. |
Amount of data transmitted | Once the connection is established, the socket s of both sides can transmit a large amount of data in a unified format. | There is a size limit when transmitting data. Each transmitted datagram must be limited to 64KB. |
characteristic | TCP has large transmission volume and strong reliability. | UDP has simple operation and high transmission efficiency. |
Java support | ServerSocket,Socket | DatagramSocket,DatagramPacket |
Why is TCP called a reliable connection oriented protocol
- The connection process of TCP protocol is as follows: set host a to establish a connection with host B. host a first sends a special "connection request message segment" to B. after receiving the message, B allocates corresponding resources (reception cache and transmission cache) to the TCP connection, and then sends a "connection permission message segment" to A. after receiving the message segment, a also allocates corresponding resources and then sends it to B "Confirmation message segment", which establishes a TCP connection and can transmit data to each other. The connection between a and B should exchange messages three times continuously (three handshakes) to ensure the reliability of connection transmission.
- UDP completely relies on IP protocol and is a connectionless protocol. Each datagram is independent information and may be transmitted to the destination through any possible path. The reliability of transmission cannot be guaranteed.
Multi client / server communication based on TCP Socket
- During Socket programming, the destination address and port number need to be pointed out when creating the Socket object
client
import java.io.*; import java.net.*; public class TalkClient { public static void main(String args[]) { try{ //Make a client request to the 4700 port of this machine Socket socket=new Socket("127.0.0.1",4700); //The BufferedReader object is constructed from the system standard input device BufferedReader sin=new BufferedReader(new InputStreamReader(System.in)); //Get the output stream from the Socket object and construct the PrintWriter object PrintWriter os=new PrintWriter(socket.getOutputStream()); //Get the input stream from the Socket object and construct the corresponding BufferedReader object BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream())); String readline; readline=sin.readLine(); //Reads a string from the system standard input while(!readline.equals("bye")){//If the string read from standard input is "bye", stop the loop //Output the string read from the system standard input to the Server os.println(readline); os.flush();//Refresh the output stream so that the Server receives the string immediately //Print the read string on the system standard output System.out.println("Client:"+readline); //Read a string from the Server and print it to standard output System.out.println("Server:"+is.readLine()); readline=sin.readLine(); //Reads a string from the system standard input } //Continue the cycle os.close(); //Close Socket output stream is.close(); //Close Socket input stream socket.close(); //Close Socket }catch(Exception e) { System.out.println("Error"+e); //If an error occurs, the error message is printed } } }
Server side
import java.io.*; import java.net.*; public class MultiTalkServer{ static int clientnum=0; //Static member variable, which records the number of current customers public static void main(String args[]) throws IOException { ServerSocket serverSocket=null; boolean listening=true; try{ //Create a ServerSocket to listen to customer requests on port 4700 serverSocket=new ServerSocket(4700); }catch(IOException e) { System.out.println("Could not listen on port:4700."); //Error, print error message System.exit(-1); //sign out } while(listening){ //Loop listening //Listen to the customer request, create a service thread according to the obtained Socket object and customer count, and start it new ServerThread(serverSocket.accept(),clientnum).start(); clientnum++; //Increase customer count } serverSocket.close(); //Close ServerSocket } }
Server side thread
import java.io.*; import java.net.*; public class ServerThread extends Thread{ Socket socket=null; //Save the Socket object related to this thread int clientnum; //Save customer count for this process public ServerThread(Socket socket,int num) { //Constructor this.socket=socket; //Initialize socket variable clientnum=num+1; //Initializing the clientnum variable } public void run() { //Thread body try{ String line; //Get the input stream from the Socket object and construct the corresponding BufferedReader object BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream())); //Get the output stream from the Socket object and construct the PrintWriter object PrintWriter os=new PrintWriter(socket.getOutputStream()); //The BufferedReader object is constructed from the system standard input device BufferedReader sin=new BufferedReader(new InputStreamReader(System.in)); //Print the string read in from the client on standard output System.out.println("Client:"+ clientnum +is.readLine()); //Read a string from standard input line=sin.readLine(); while(!line.equals("bye")){//If the string is "bye", stop the loop os.println(line);//Output the string to the client os.flush();//Refresh the output stream so that the Client receives the string immediately //Print the string on the system standard output System.out.println("Server:"+line); //Read a string from the Client and print it to standard output System.out.println("Client:"+ clientnum +is.readLine()); line=sin.readLine();//Reads a string from the system standard input }//Continue the cycle os.close(); //Close Socket output stream is.close(); //Close Socket input stream socket.close(); //Close Socket }catch(Exception e){ System.out.println("Error:"+e);//Error, print error message } } }
Multi client / server communication based on UDP datagram
- When using datagram, the destination address and port need to be indicated in the construction method when creating datagram packet object
client
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.io.BufferedReader; import java.io.InputStreamReader; public class QuoteClient { public static void main(String[] args) throws IOException { if (args.length != 1) { // If the Server name is not given at startup, output an error message and exit System.out.println("Usage:java QuoteClient <hostname>"); return; } DatagramSocket socket = new DatagramSocket();// Establish datagram socket byte[] buf = new byte[256]; // Create buffer // The first parameter given by the command line defaults to the domain name of the Server, through which the IP information of the Server is obtained InetAddress address = InetAddress.getByName(args[0]); // Create DatagramPacket object DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); // send out // Create a new datagram packet object to receive datagrams packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // receive // Generate the corresponding string according to the received byte array String received = new String(packet.getData()); // Output the generated string System.out.println("Quote of the Moment:" + received); socket.close(); // Close data socket DatagramSocket socket=new DatagramSocket();//Create datagram socket BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); String readLine; InetAddress address=InetAddress.getByName("127.0.0.1");//IP information for Server while(!(readLine = sin.readLine()).equals("bye")) { byte[] buf = readLine.getBytes(); //Create DatagramPacket object DatagramPacket packet=new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); //send out buf = new byte[256]; //Create a new datagram packet object to receive datagrams packet=new DatagramPacket(buf,buf.length); socket.receive(packet); //receive buf = packet.getData(); //Generate the corresponding string according to the received byte array String received=new String(buf); //Print the generated string System.out.println("Quote of the Sever: "+received ); } socket.close(); //Close socket } }
Server side
public class QuoteServer { public static void main(String args[])throws java.io.IOException{ new QuoteServerThread().start();// Start a QuoteServerThread thread } }
Server side thread
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 QuoteServerThread extends Thread// Server thread { protected DatagramSocket socket = null;// DatagramSocket protected BufferedReader in = null;// Reader protected boolean moreQuotes = true;// Flag variable. Continue public QuoteServerThread() throws IOException {// this("QuoteServerThread");// QuoteServerThread } public QuoteServerThread(String name) throws IOException { super(name); // socket = new DatagramSocket(4445);// Create datagram socket port 4445 in = new BufferedReader(new InputStreamReader(System.in)); } public void run() // Thread body { while (moreQuotes) { try { byte[] buf = new byte[256]; // Create buffer DatagramPacket packet = new DatagramPacket(buf, buf.length); // Building DatagramPacket objects from buffers socket.receive(packet); // Receive datagram // Output content sent by client System.out.println(new String(packet.getData())); // Get the input content from the screen as the content sent to the client String dString = in.readLine(); // If it is bey, exit after sending a message to the client if (dString.equals("bye")) { moreQuotes = false; } buf = dString.getBytes();// Convert a String into a byte array for transfer // Get the Client address from the Packet transmitted from the Client InetAddress address = packet.getAddress(); int port = packet.getPort(); // Port number // Build datagram packet based on client information packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); // Send datagram } catch (IOException e) { // exception handling e.printStackTrace(); // Output exception stack information moreQuotes = false; // Flag variable is set to false to end the loop } } socket.close(); // Close datagram socket } }
Programming with urlconnection object
Use urlconnection object programming to return to the home page of the website, and store the content of the home page in the file
import java.io.*; import java.net.*; public class Test { public static void main(String[] args) throws IOException { URL url= new URL("https://www.luogu.com.cn/"); URLConnection con = url.openConnection(); //Build character stream BufferedReader is= new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); FileOutputStream fos = new FileOutputStream("D:/luogu.html"); // The file with the specified path will be automatically created String line; while((line = is.readLine()) != null ) { line = line + "\n"; fos.write(line.getBytes("UTF-8")); fos.flush(); } is.close(); fos.close(); } }