Java Advanced Chapter - Network Communication

I will give

Java Advanced (2) - Network Communication

  Network programming is the core part of every developer's tool. After learning a lot of Java knowledge, we will also step into several major directions. Java network programming is one of them.

  There are no more programs today that emphasize networking than those that involve networking. With the exception of classic applications such as e-mail, web browsers, and telnet, most major applications have some level of NET functionality. For example, our most commonly used IDE (Eclipse/IDEA) communicates with source code repositories (GitHub, etc.); another example is Word, which can open files from a URL; or the many online games we play, where players play against each other in real time, etc. Wait. Java was the first programming language designed for network applications from the very beginning. One of the first two practical Java applications was a web browser. With the continuous development of the Internet, Java has become the only suitable language for building next-generation networks. The language of the application. (Excerpt from Java NetWork Programming by Elliotte Rusty Harold )

1. Client/Server

  In order to realize the communication between two computers, it is necessary to use a network line to connect the two computers. The server (Server) refers to the computer or program that provides information, the client (Client) refers to the computer or program that requests information, and the network is used to connect the server and the client computer to communicate with each other.

  Let's look at a simple communication example.

  The following Server program is a server-side application that uses Socket to listen on a specified port.

copy code

 1 import java.io.IOException; 2 import java.io.InputStreamReader; 3 import java.io.Reader; 4 import java.net.ServerSocket; 5 import java.net.Socket; 6  7 public class Server { 8  9     public static void main(String[] args) throws IOException {10         int port = 9999;11         12         System.out.println("-----------客户端启动-----------");13         14         ServerSocket server = new ServerSocket(port);15         Socket socket = server.accept();16         Reader reader = new InputStreamReader(socket.getInputStream());17         char chars[] = new char[1024];18         int len;19         StringBuilder builder = new StringBuilder();20         while ((len=reader.read(chars)) != -1) {21            builder.append(new String(chars, 0, len));22         }23         System.out.println("收到来自客户端的信息: " + builder);24         reader.close();25         socket.close();26         server.close();27     }28 29 }

copy code

   The following Client is a client program that connects to the server through socket and sends a request, and then waits for a response.

copy code

 1 import java.io.IOException; 2 import java.io.OutputStreamWriter; 3 import java.io.Writer; 4 import java.net.Socket; 5 import java.util.Scanner; 6  7 public class Client { 8  9     public static void main(String[] args) throws IOException {10         String host = "127.0.0.1";11         int port = 9999;12         13         System.out.println("-----------服务器启动-----------");14         15         Socket client = new Socket(host, port);16         Writer writer = new OutputStreamWriter(client.getOutputStream());17         Scanner in = new Scanner(System.in);18         writer.write(in.nextLine());19         writer.flush();20         writer.close();21         client.close();22         in.close();23     }24     25 }

copy code

  Start the server first, and the results are as follows:

  

  Run the client again, and enter the information to be sent, as follows:

  

  At this point, the Server receives the message sent by the Client, as follows:

  

  This is a simple socket communication, see TCP below for specific analysis.

2. TCP

  TCP network programming refers to the use of the Socket class to write communication programs. For specific examples, refer to the above example.

  Sockets provide a communication mechanism between two computers using TCP. The client program creates a socket and tries to connect to the server's socket. When the connection is established, the server creates a Socket object. Clients and servers can now communicate by writing to and reading from Socket objects. The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for server programs to listen for clients and establish connections with them.

  The steps to establish a TCP connection between two computers using sockets are as follows:

  • The server instantiates a ServerSocket object that represents communication over a port on the server.

  • The server calls the accept() method of the ServerSocket class, which will wait until the client connects to the given port on the server.

  • While the server is waiting, a client instantiates a Socket object, specifying the server name and port number to request a connection.

  • The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, a Socket object is created on the client side to be able to communicate with the server.

  • On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.

  After the connection is established, the I/O stream is used for communication. Each socket has an output stream and an input stream. The output stream of the client is connected to the input stream of the server, and the input stream of the client is connected to the output stream of the server.

  1. InetAddress

  The InetAddress class in the java.net package is a class related to IP addresses, which can be used to obtain IP addresses, host addresses and other information.

InetAddress ip = InetAddress.getLocalHost();
String localName = ip.getHostName(); //Get the local host name String localIp = ip.getHostAddress(); //Get the ip address of the local host

  2. ServerSocket 

  The ServetSocket class in the java.net package is used to represent a server socket. Its main function is to wait for "requests" from the network. It can wait for a connected socket through a specified port (such as 9999 in the example above) .

  The server socket can be connected to one socket at a time. If multiple clients make connection requests at the same time, the server socket will store the client requesting connection in the queue, and then take out a socket from it to communicate with the server. The newly created socket is connected. If the number of requested connections is greater than the maximum number of connections, the excess connection requests will be rejected.

  For the specific method of ServerSocket, please refer to the API, and here is only a description of the accept() method. Calling the accept() method will return a Socket object connected to the client Socket object. The output stream object obtained by the server-side Socket object using the getOutputStream() method will point to the input stream object obtained by the client-side Socket object using the getInputStream() method. vice versa.

  It should be noted that the accept() method will block the continued execution of the thread until the client's call is accepted. If there is no client calling the server, the following code will not be executed.

3. UDP

  User Datagram Protocol (UDP) is another form of network information transmission. UDP-based communication is different from TCP-based communication. UDP's information transfer is faster, but it does not provide reliable guarantees.

  1. DatagramPacket

  The DatagramPacket class in the java.net package is used to represent data packets. The construction method is as follows:

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

  In the above construction methods, the first one specifies the memory space and size of the data packet, and the second one specifies not only the memory space and size of the data packet, but also the destination address and port of the data packet.

  2. DatagramSocket

  The DatagramSocket class in the java.net package is used to represent the socket for sending and receiving data packets. The construction method is as follows:

DatagramSocket()
DatagramSocket(int port)
DatagramSocket(int port, InetAddress addr)

  Of the above construction methods, the first creates a packet socket and binds it to any available port on the localhost , the second creates a packet socket and binds it to a specified port on the localhost , Creates a packet socket and binds it to the specified local address .

 4. Example test

  Write a complete example below, the title is as follows:

  • Establish a server-side program, and the server-side program receives the request from the client;

  • Download the program from the Internet, 900 English sentences, each sentence occupies one line;

  • The server reads the file and saves it to a collection or list;

  • Create a client program to generate data using the format of "sentence: <number#>, <number#>". For example: send "sentense:1,2,3", the server sends the corresponding numbered sentences to the client and presents them;

  • The client needs to save the sentence sent by the server. If the corresponding sentence has been saved, it will not be saved;

  • The client needs to store the data obtained from the server in a file.

   1. Program structure

  

  2. Server.java

  This class is the client class.

copy code

 1 import java.io.*; 2 import java.net.ServerSocket; 3 import java.net.Socket; 4 import java.util.ArrayList; 5 import java.util.List; 6  7 /** 8  * 
 9  * @author adamjwh10  *11  */12 public class Server {13     14     public static List<String> sentence;15     private static String filename = "src/com/adamjwh/jnp/ex6_2/English900.txt";16     17     public static void main(String[] args) throws IOException {18         sentence=new ArrayList<>();19         System.out.println("-----------服务器启动-----------");20         21         FileReader fileReader = new FileReader(filename);22         BufferedReader br = new BufferedReader(fileReader);23         24         String inputLine = null;25         while ((inputLine = br.readLine()) != null) {26             sentence.add(inputLine);27         }28 29         ServerSocket ss = new ServerSocket(9999);30         while(true){31             Socket sk =ss.accept();32             ServerThread st = new ServerThread(sk);33             st.start();34         }35         36     }37 }

copy code

  2. Client.java

  This class is the server class.

copy code

import java.io.BufferedReader;import java.io.FileWriter;import java.io.InputStream;import java.io.InputStreamReader;import java.io.PrintStream;import java.net.Socket;import java.util.Scanner;/**
 * 
 * @author adamjwh
 * */public class Client {    
    private static String filename = "src/com/adamjwh/jnp/ex6_2/result.txt";    
    public static void main(String[] args) {        try {
            Socket sk = new Socket("127.0.0.1", 9999);
            System.out.println("-----------client startup----------");

            PrintStream ps = new PrintStream(sk.getOutputStream());
            System.out.print("Send: ");
            Scanner sn = new Scanner(System.in);
            String str = sn.nextLine();
            ps.println (p);

            InputStream is = sk.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);            
            //write file
            FileWriter fw = new FileWriter(filename, true); //Read file
            String result = new ReadFile().readFile(filename);
            
            String s;            while ((s = br.readLine()) != null) {
                System.out.println("Server push: " + s); if(!result.contains(s)) {
                    fw.write(s + "\n");
                }
            }

            sk.shutdownInput();
            ps.close();
            sk.close();
            fw.close();

        } catch (Exception e) {
            e.printStackTrace ();
        }

    }
}

copy code

  3. ServerThread

  Information exchange is achieved through threads.

copy code

 1 import java.io.*; 2 import java.net.Socket; 3  4 /** 5  * 
 6  * @author adamjwh 7  * 8  */ 9 public class ServerThread extends Thread{10     Socket sk;11     public ServerThread(Socket sk){12         this.sk= sk;13     }14     public void run() {15         BufferedReader br=null;16         try{17             br  = new BufferedReader(new InputStreamReader(sk.getInputStream()));18             String line = br.readLine();19             System.out.println("客户端:"+line);20             String[] split = line.split(":");21             String[] split1 = split[split.length - 1].split(",");22             sk.shutdownInput();23 24             OutputStream os = sk.getOutputStream();25 26             PrintStream bw = new PrintStream(os);27 28             //给客户端返回信息29             for(int i=0;i<split1.length;i++) {30                 bw.print(Server.sentence.get(Integer.parseInt(split1[i])%Server.sentence.size())+"\n");31             }32             bw.flush();33             br.close();34             sk.close();35         }36         catch(IOException e){37             e.printStackTrace();38         }39     }40 }

copy code

   4. Running Results

  run the server first

  

  Run the client again and enter the information

  

  The server receives the request from the client

  

   The server pushes the request result to the client, where the client obtains the 174th, 258th, and 5th sentences of its request and outputs it to the file

  

  I tested the test file here to 162 (that is, the 15th line of the file). You can see that two new lines of sentences (174 and 258) have been added to the file, and the 5th sentence has already appeared before ( Line 1 of the file), so without appending the 5th sentence, complete the above title.

  


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324605097&siteId=291194637