An example of Java TCP network communication

  • 2020-04-01 02:03:21
  • OfStack

There are two main types of network programming modes in JAVA, TCP and UDP. TCP is an instant communication, UDP is to communicate through packets, and UDP involves the analysis and transmission of data. In terms of security performance, TCP is better than others. Data loss is not easy to occur in the communication process. If one party interrupts, the communication between the two parties will end. In terms of efficiency, UDP is not only a little bit faster than TCP, if the terminal has a function to parse the data method, the packets will be sent continuously, and then feedback back.
The above is my own understanding, the following is about the TCP protocol communication of the two classes;
The Server class:

package TCP;
import java.io.*;
import java.net.*;
import javax.swing.*;
 public class Server {
     //Input stream on the server side
    static  BufferedReader br;
     //The output stream on the server side
    static  PrintStream ps;
     //Server-related interface components
    static  JTextArea text;    
            JFrame frame;

    public Server(){
        //Instantiation of the interface on the server side
        JFrame frame=new JFrame(" The server side ");
        text=new JTextArea();
        JScrollPane scroll =new JScrollPane(text);
        frame.add(scroll);
        frame.setVisible(true);
        frame.setSize(300,400);
        //Setting the server-side text box here is not editable
        text.setEditable(false);
    }

    public static void main(String[] args) throws Exception{       
        new Server();    //Generate server interface
        //Through the server-side constructor & NBSP; ServerSocket(port) instantiates a server port
        ServerSocket server=new ServerSocket(2000); 
        text.append(" Listening to the 2000 port "+"n");
        //Instantiate an object that accepts server data
        Socket client=server.accept();
        br =new BufferedReader(new InputStreamReader(client.getInputStream()));
        ps =new PrintStream(client.getOutputStream());        
        String msg;
        //If the input stream is not empty, the received information is printed into the corresponding text box and the returned information is fed back
        while ((msg =br.readLine())!=null)  
        {
            text.append(" Server side received: "+msg+"n");
            ps.println(msg);
            if(msg.equals("quit"))
            {   
                text.append(" The client" 2000 "Quit! "+"n");
                text.append(" The server program will exit! ");                
                break;
            }
        }
        ps.close();
        br.close();
        client.close();
    }
}

Client:

package TCP;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.net.*;
public class Client implements ActionListener{
   //There are two graphical interfaces, one is the frame that is connected and the other is frame1& NBSP; that communicates with the server.    
    private  JFrame frame;
    private  JLabel adress;
    private  JLabel port;
             JTextField adresstext;
             JTextField porttext;
             JButton connect;

    private JFrame frame1;
    private JLabel shuru;
    private JPanel panel1;
    private JPanel panel2;
    private JLabel jieshou;
            JButton send;
    static JTextArea shurukuang;
    static TextArea jieshoukuang;

    //The data stream received from the server
    static BufferedReader br1;
    //Data flow from client output
    static PrintStream ps;
    //The data stream received from the input box in the communication interface
    static BufferedReader br2;
    static Socket client;
    //Converts the input field string to the input stream of the string stream required by the string stream
    static ByteArrayInputStream stringInputStream ;

   public Client() {
       //Instantiation of the connection interface
        frame=new JFrame();
        adress=new JLabel("IP  address ");
        port =new JLabel(" The port number ");
        adresstext=new JTextField("127.0.0.1",10);
        porttext=new JTextField("2000",10);
        connect=new JButton(" The connection ");
            //The layout of the connection interface & NBSP;                  
        frame.setLayout(new FlowLayout());
        frame.add(adress);
        frame.add(adresstext);
        frame.add(port);   
        frame.add(porttext);
        frame.add(connect);
        frame.setVisible(true);
        frame.setSize(200,150);           
        connect.addActionListener(this);
          //Instantiation of the communication interface
        frame1=new JFrame();
        shuru=new JLabel(" Please enter the ");
          shurukuang=new JTextArea(" Please enter ",5,40);  

          panel1=new JPanel();
          panel1.add(shuru);
          panel1.add(shurukuang);
          panel1.setLayout(new FlowLayout());

          send=new JButton(" send "); 
          panel2=new JPanel();
          jieshou=new JLabel(" Have accepted ");

         jieshoukuang=new TextArea(8,60);     
          jieshoukuang.setEditable(false);

          panel2.add(jieshou);
          panel2.add(jieshoukuang);
          panel2.setLayout(new FlowLayout());        
          frame1.setLayout(new FlowLayout());
              //Communication interface layout
          frame1.add(BorderLayout.NORTH,panel1);
          frame1.add(send);
          frame1.add(BorderLayout.SOUTH,panel2);
             //The communication interface is not visible when connecting
          frame1.setVisible(false);
          frame1.setSize(500,350);
          send.addActionListener(this);  
            }
         //There is a corresponding button time in both interfaces to add actions for the corresponding time
      public  void  actionPerformed(ActionEvent e) {
         if(e.getSource()==connect){    
          try {
                  //When the connection button is triggered, a client is instantiated
                client=new Socket("127.0.0.1",2000);    
                  //Hide the connection interface and show the communication interface
                frame.setVisible(false);
                frame1.setVisible(true);
                jieshoukuang.append(" The server is connected! "+"n");            
           } catch (IOException e1){
                 System.out.println(" Link failed! ");
                e1.printStackTrace(); 
             }
         }
         //The corresponding time processing of the send button in the communication interface
        if(e.getSource()==send){
              //Converts a string in the input box to a string stream
             stringInputStream = new ByteArrayInputStream((shurukuang.getText()).getBytes()); 
             br2 =new BufferedReader(new InputStreamReader(stringInputStream));
             String msg;
             try{
              while((msg=br2.readLine())!=null){    
                  ps.println(msg);   //Sends the contents of the input box to the server & NBSP;            
                  jieshoukuang.append(" Send to the server: "+msg+"n");
                  jieshoukuang.append(" The client accepts the response :"+br1.readLine()+"n");
                  if(msg.equals("quit"))
                     {
                        jieshoukuang.append(" The client will exit !");
                        br1.close();
                        ps.close();
                        client.close();
                        frame1.setVisible(false);
                        break;
                           }                      
                      }    
             }catch(IOException e2){
                 System.out.println(" Error reading input field data! ");                  
              }
             shurukuang.setText("");
          }
      }  

      public static void main(String[] args) throws IOException{
           new Client();  //Instantiate the connection interface
           client=new Socket("127.0.0.1",2000);             
           //Data received from the server
           br1=new BufferedReader(new InputStreamReader(client.getInputStream()));
            //Data output from the client
           ps =new PrintStream(client.getOutputStream());          
              }
        }

After writing these two classes, I still have a few questions:
1) why does the main function have to be static?
2) why can't the BufferedReader be used to judge directly and assign the read data to the string for operation?
3) in the Connect button event in the connection interface, I instantiate a client object, but I comment out the client=new Socket in the main function ("127.0.0.1",2000); NULLPOINTEXCEPTION, which I don't understand.
I hope all of you who have read this article will not be afraid to give your advice. I am also reading "Think in Java" to find my answer in a corner.

Related articles: