Home Java javaTutorial Detailed explanation of examples based on java TCP network communication

Detailed explanation of examples based on java TCP network communication

Jan 05, 2017 pm 02:31 PM

There are two main network programming modes designed in JAVA: TCP and UDP. TCP belongs to instant communication, and UDP communicates through data packets. UDP involves the analysis and transmission of data. In terms of security performance, TCP is slightly better. Data loss is not easy to occur during the communication process. If one party is interrupted, the communication between the two parties will end. During the transmission of UDP data packets, if one party is interrupted, the data packet will have a large loss. It may be lost, and the order of the transmitted data packets may be out of order; in terms of efficiency, UDP is not just a little bit faster than TCP. If the terminal has a function to parse the data, the data packets will continue to flow. Send it over and feed it back.
The above is my own understanding. The following are two classes about TCP protocol communication;
Server class:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

package TCP;

import java.io.*;

import java.net.*;

import javax.swing.*;

 public class Server {

     //服务器端的输入流

    static  BufferedReader br;

     //服务器端的输出流

    static  PrintStream ps;

     //服务器相关的界面组件

    static  JTextArea text;   

            JFrame frame;

 

    public Server(){

        //服务器端的界面的实例化

        JFrame frame=new JFrame("服务器端");

        text=new JTextArea();

        JScrollPane scroll =new JScrollPane(text);

        frame.add(scroll);

        frame.setVisible(true);

        frame.setSize(300,400);

        //这里设置服务器端的文本框是不可编辑的

        text.setEditable(false);

    }

 

    public static void main(String[] args) throws Exception{      

        new Server();    //生成服务器界面

        //通过服务器端构造函数  ServerSocket(port) 实例化一个服务器端口

        ServerSocket server=new ServerSocket(2000);

        text.append("监听2000端口"+"\n");

        //实例化一个接受服务器数据的对象

        Socket client=server.accept();

        br =new BufferedReader(new InputStreamReader(client.getInputStream()));

        ps =new PrintStream(client.getOutputStream());       

        String msg;

        //如果输入流不为空,将接受到的信息打印到相应的文本框中并反馈回收到的信息

        while ((msg =br.readLine())!=null) 

        {

            text.append("服务器端收到:"+msg+"\n");

            ps.println(msg);

            if(msg.equals("quit"))

            {  

                text.append("客户端“2000”已退出!"+"\n");

                text.append("服务器程序将退出!");               

                break;

            }

        }

        ps.close();

        br.close();

        client.close();

    }

}

Copy after login

Client class:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

package TCP;

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import javax.swing.*;

import java.net.*;

public class Client implements ActionListener{

   //这里有两个图形界面,一个是连接的frame,另一个和服务器通信的界面frame1   

    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;

 

    //从服务端接受的数据流

    static BufferedReader br1;

    //从客户端输出的数据流

    static PrintStream ps;

    //从通信界面中的输入框接受的数据流

    static BufferedReader br2;

    static Socket client;

    //将输入框字符串转换为字符串流所需的字符串的输入流

    static ByteArrayInputStream stringInputStream ;

 

   public Client() {

       //连接界面的实例化

        frame=new JFrame();

        adress=new JLabel("IP 地址");

        port =new JLabel("端口号");

        adresstext=new JTextField("127.0.0.1",10);

        porttext=new JTextField("2000",10);

        connect=new JButton("连接");

            //连接界面的布局          

        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);

          //通信界面的实例化

        frame1=new JFrame();

        shuru=new JLabel("请输入");

          shurukuang=new JTextArea("请输入····",5,40); 

 

          panel1=new JPanel();

          panel1.add(shuru);

          panel1.add(shurukuang);

          panel1.setLayout(new FlowLayout());

 

          send=new JButton("发送");

          panel2=new JPanel();

          jieshou=new JLabel("已接受");

 

         jieshoukuang=new TextArea(8,60);    

          jieshoukuang.setEditable(false);

 

          panel2.add(jieshou);

          panel2.add(jieshoukuang);

          panel2.setLayout(new FlowLayout());       

          frame1.setLayout(new FlowLayout());

              //通信界面都的布局

          frame1.add(BorderLayout.NORTH,panel1);

          frame1.add(send);

          frame1.add(BorderLayout.SOUTH,panel2);

             //连接时通信界面是处于看不到的

          frame1.setVisible(false);

          frame1.setSize(500,350);

          send.addActionListener(this); 

            }

         //两个界面当中都有相应的按钮时间,为相应的时间添加动作

      public  void  actionPerformed(ActionEvent e) {

         if(e.getSource()==connect){   

          try {

                  //当触发连接按钮时,实例化一个客户端

                client=new Socket("127.0.0.1",2000);   

                  //隐藏连接界面,显示通信界面

                frame.setVisible(false);

                frame1.setVisible(true);

                jieshoukuang.append("已经连接上服务器!"+"\n");           

           } catch (IOException e1){

                 System.out.println("链接失败!");

                e1.printStackTrace();

             }

         }

         //通信界面中的发送按钮相应的时间处理

        if(e.getSource()==send){

              //将输入框中的字符串转换为字符串流

             stringInputStream = new ByteArrayInputStream((shurukuang.getText()).getBytes());

             br2 =new BufferedReader(new InputStreamReader(stringInputStream));

             String msg;

             try{

              while((msg=br2.readLine())!=null){   

                  ps.println(msg);   //将输入框中的内容发送给服务器端       

                  jieshoukuang.append("向服务器发送:"+msg+"\n");

                  jieshoukuang.append("客户端接受相应:"+br1.readLine()+"\n");

                  if(msg.equals("quit"))

                     {

                        jieshoukuang.append("客户端将退出!");

                        br1.close();

                        ps.close();

                        client.close();

                        frame1.setVisible(false);

                        break;

                           }                     

                      }   

             }catch(IOException e2){

                 System.out.println("读输入框数据出错!");                 

              }

             shurukuang.setText("");

          }

      

 

      public static void main(String[] args) throws IOException{

           new Client();  //实例化连接界面

           client=new Socket("127.0.0.1",2000);            

           //从服务端接受的数据 

           br1=new BufferedReader(new InputStreamReader(client.getInputStream()));

            //从客户端输出的数据

           ps =new PrintStream(client.getOutputStream());         

              }

        }

Copy after login


Finished There are still several questions for these two classes in the future:
1) Why does the main function have to be modified with static?
2) Why can’t the buffer object BufferedReader be used directly for judgment? The read data must be assigned to a string for operation?
3) In the Connect button event in the connection interface, I instantiated a client object, but when I commented out the sentence client=new Socket("127.0.0.1",2000); in the main function, You will find that a NULLPOINTEXCEPTION exception is thrown. I don’t understand it?
I hope that some experts who read this article can give me some advice. I am also constantly flipping through "Think in java" hoping to find my answer in some inconspicuous corner.

For more detailed examples of Java TCP network communication and related articles, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Mar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20: Key Performance Boosts and New Features Node.js 20: Key Performance Boosts and New Features Mar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Iceberg: The Future of Data Lake Tables Iceberg: The Future of Data Lake Tables Mar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Mar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How can I implement functional programming techniques in Java? How can I implement functional programming techniques in Java? Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

See all articles