Home  >  Article  >  Java  >  How to implement a simple chat program based on TCP in Java

How to implement a simple chat program based on TCP in Java

王林
王林forward
2023-05-04 10:34:061577browse

1. How to implement TCP communication

To implement TCP communication, you need to create a server-side program and a client program. In order to ensure the security of data transmission, you first need to implement the server-side program, and then write the client terminal program.

Run the server program on the local machine and run the client program on the remote machine

The IP address of the local machine: 192.168.129.222

How to implement a simple chat program based on TCP in Java

IP address of the remote machine: 192.168.214.213

How to implement a simple chat program based on TCP in Java

2. Write C/S architecture chat program

1. Write server-side program - Server.java

Create the Server class in the net.hw.network package

How to implement a simple chat program based on TCP in Java

package net.hw.network;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 功能:服务器端
 * 作者:华卫
 * 日期:2022年03月18日
 */
public class Server extends JFrame {
    static final int PORT = 8136;
    static final String HOST_IP = "192.168.129.222";

    private JPanel panel1, panel2;
    private JTextArea txtContent, txtInput, txtInputIP;
    private JScrollPane panContent, panInput;
    private JButton btnClose, btnSend;

    private ServerSocket serverSocket;
    private Socket socket;
    private DataInputStream netIn;
    private DataOutputStream netOut;

    public static void main(String[] args) {
        new Server();
    }

    public Server() {
        super("服务器");

        //创建组件
        panel1 = new JPanel();
        panel2 = new JPanel();
        txtContent = new JTextArea(15, 60);
        txtInput = new JTextArea(3, 60);
        panContent = new JScrollPane(txtContent, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        panInput = new JScrollPane(txtInput, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        btnClose = new JButton("关闭");
        btnSend = new JButton("发送");

        //添加组件
        getContentPane().add(panContent, "Center");
        getContentPane().add(panel1, "South");
        panel1.setLayout(new GridLayout(0, 1));
        panel1.add(panInput);
        panel1.add(panel2);
        panel2.add(btnSend);
        panel2.add(btnClose);

        //设置组件属性
        txtContent.setEditable(false);
        txtContent.setFont(new Font("宋体", Font.PLAIN, 13));
        txtInput.setFont(new Font("宋体", Font.PLAIN, 15));
        txtContent.setLineWrap(true);
        txtInput.setLineWrap(true);
        txtInput.requestFocus();
        setSize(450, 350);
        setLocation(50, 200);
        setResizable(false);
        setVisible(true);

        //等候客户请求	
        try {
            txtContent.append("服务器已启动...\n");
            serverSocket = new ServerSocket(PORT);
            txtContent.append("等待客户请求...\n");
            socket = serverSocket.accept();
            txtContent.append("连接一个客户。\n" + socket + "\n");
            netIn = new DataInputStream(socket.getInputStream());
            netOut = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        /

        //注册监听器,编写事件代码	
        txtContent.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayClientMsg();
            }
        });

        txtInput.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayClientMsg();
            }
        });

        panel2.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayClientMsg();
            }
        });

        txtInput.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                displayClientMsg();
            }
        });

        txtInput.addFocusListener(new FocusAdapter() {
            public void focusGained(FocusEvent e) {
                displayClientMsg();
            }
        });

        btnSend.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {

                    String serverMsg = txtInput.getText();
                    if (!serverMsg.trim().equals("")) {
                        txtContent.append("服务器>" + serverMsg + "\n");
                        netOut.writeUTF(serverMsg);
                    } else {
                        JOptionPane.showMessageDialog(null, "不能发送空信息!", "服务器", JOptionPane.WARNING_MESSAGE);
                    }

                    txtInput.setText("");
                    txtInput.requestFocus();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
            }
        });

        btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    netIn.close();
                    netOut.close();
                    socket.close();
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.exit(0);
            }
        });

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                try {
                    netIn.close();
                    netOut.close();
                    socket.close();
                    serverSocket.close();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
                System.exit(0);
            }

            public void windowActivated(WindowEvent e) {
                txtInput.requestFocus();
            }
        });
    }

    //显示客户端信息
    void displayClientMsg() {
        try {
            if (netIn.available() > 0) {
                String clientMsg = netIn.readUTF();
                txtContent.append("客户端>" + clientMsg + "\n");
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

2. Write the client program - Client.java

in Create the Client class in the net.hw.network package

How to implement a simple chat program based on TCP in Java

package net.hw.network;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 功能:客户端
 * 作者:华卫
 * 日期:2022年03月18日
 */
public class Client extends JFrame {

    private JPanel panel1, panel2;
    private JTextArea txtContent, txtInput;
    private JScrollPane panContent, panInput;
    private JButton btnClose, btnSend;

    private Socket socket;
    private DataInputStream netIn;
    private DataOutputStream netOut;

    public static void main(String[] args) {
        new Client();
    }

    public Client() {
        super("客户端");

        //创建组件
        panel1 = new JPanel();
        panel2 = new JPanel();
        txtContent = new JTextArea(15, 60);
        txtInput = new JTextArea(3, 60);
        panContent = new JScrollPane(txtContent, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        panInput = new JScrollPane(txtInput, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        btnClose = new JButton("关闭");
        btnSend = new JButton("发送");

        //添加组件
        getContentPane().add(panContent, "Center");
        getContentPane().add(panel1, "South");
        panel1.setLayout(new GridLayout(0, 1));
        panel1.add(panInput);
        panel1.add(panel2);
        panel2.add(btnSend);
        panel2.add(btnClose);

        //设置组件属性
        txtContent.setEditable(false);
        txtContent.setFont(new Font("宋体", Font.PLAIN, 13));
        txtInput.setFont(new Font("宋体", Font.PLAIN, 15));
        txtContent.setLineWrap(true);
        txtInput.setLineWrap(true);
        txtInput.requestFocus();
        setSize(450, 350);
        setLocation(550, 200);
        setResizable(false);
        setVisible(true);

        //连接服务器
        try {
            txtContent.append("连接服务器...\n");
            socket = new Socket(Server.HOST_IP, Server.PORT);
            txtContent.append("连接服务器成功。\n" + socket + "\n");
            netIn = new DataInputStream(socket.getInputStream());
            netOut = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e1) {
            JOptionPane.showMessageDialog(null, "服务器连接失败!\n请先启动服务器程序!", "客户端", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }

        /

        //注册监听器,编写事件代码
        txtContent.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayServerMsg();
            }
        });

        txtInput.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayServerMsg();
            }
        });

        panel2.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                displayServerMsg();
            }
        });

        txtInput.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                displayServerMsg();
            }
        });

        txtInput.addFocusListener(new FocusAdapter() {
            public void focusGained(FocusEvent e) {
                displayServerMsg();
            }
        });

        btnSend.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {

                    String clientMsg = txtInput.getText();
                    if (!clientMsg.trim().equals("")) {
                        netOut.writeUTF(clientMsg);
                        txtContent.append("客户端>" + clientMsg + "\n");
                    } else {
                        JOptionPane.showMessageDialog(null, "不能发送空信息!", "客户端", JOptionPane.WARNING_MESSAGE);
                    }

                    txtInput.setText("");
                    txtInput.requestFocus();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
            }
        });

        btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    netIn.close();
                    netOut.close();
                    socket.close();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
                System.exit(0);
            }
        });

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                try {
                    netIn.close();
                    netOut.close();
                    socket.close();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
                System.exit(0);
            }

            public void windowActivated(WindowEvent e) {
                txtInput.requestFocus();
            }
        });
    }

    //显示服务端信息
    void displayServerMsg() {
        try {
            if (netIn.available() > 0) {
                String serverMsg = netIn.readUTF();
                txtContent.append("服务器>" + serverMsg + "\n");
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

3. Test whether the server and the client can communicate

On this machine[192.168.129.222 ]

How to implement a simple chat program based on TCP in Java

Start the client on the remote machine [192.168.214.213]

How to implement a simple chat program based on TCP in Java

Display the connection server [192.168.129.222] Successful, switch to the server to view, it shows that a client is connected [192.168.214.213]

How to implement a simple chat program based on TCP in Java

##At this time, the server and the client can communicate with each other

How to implement a simple chat program based on TCP in Java

#4. Program optimization ideas - using multi-threading on the server side

In fact, many server-side programs are allowed to be accessed by multiple applications. For example, a portal website can be accessed by multiple users at the same time, so the server side is multi-threaded.

How to implement a simple chat program based on TCP in Java

The above is the detailed content of How to implement a simple chat program based on TCP in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete