当前位置: 代码迷 >> java >> 通过从另一个文件无法运行来调用客户端文件的Java聊天应用程序
  详细解决方案

通过从另一个文件无法运行来调用客户端文件的Java聊天应用程序

热度:81   发布时间:2023-07-31 11:28:09.0

当我直接运行客户端文件时,我正在开发一个多客户端聊天应用程序的项目,但是它工作正常,但是当我尝试从其他文件(例如新的jframe)中调用它时,它却无法正常工作。

ChatClientGuiTEST.java

    enter code here
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package chating;

import java.awt.Frame;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.DefaultCaret;

/**
 *
 * @author Hello
 */
public class ChatClientGuiTEST extends javax.swing.JFrame {

    BufferedReader in;
    PrintWriter out;
    ResultSet rs;
    //SignUp obj;

    public ChatClientGuiTEST() throws IOException {
        initComponents();
        pack();
        setSize(406, 600);
        setResizable(false);

        //jLabel2.setText(usern);
        jLabel2.setVisible(true);
        //jTextArea1.setVisible(false);

        jTextField1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if (jTextField1.getText().trim().length() != 0) {
                    try {
                        out.println(jTextField1.getText());
                    } catch (Exception ev) {
                        System.out.println(ev);
                    }
                    jTextField1.setText("");
                }
            }
        });
        jTextField1.requestFocusInWindow();

        try {
            connection obj = new connection();
            String query = "SELECT * FROM tb_online";
            connection.pst = connection.con.prepareStatement(query);
            rs = connection.pst.executeQuery();

            while (rs.next()) {

                String online_user = rs.getString("online_user");
                Object[] row = {online_user};
                DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
                model.addRow(row);

            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "UNABLE TO FETCH DATA" + e, "ERROR", 0);
        }
        this.setVisible(true);
        //run();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField1);
        jTextField1.setBounds(0, 530, 400, 40);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setMinimumSize(new java.awt.Dimension(4, 400));
        jTextArea1.setSelectionColor(new java.awt.Color(51, 0, 51));
        jScrollPane1.setViewportView(jTextArea1);
        jTextArea1.setEditable(false);
        jTextArea1.setLineWrap(true);
        DefaultCaret caret = (DefaultCaret)jTextArea1.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(0, 70, 400, 460);

        jLabel2.setText("jLabel1");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(340, 390, 50, 14);

        jLabel1.setFont(new java.awt.Font("Urdu Typesetting", 3, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("WELCOME          USER          TO          CHATZONE");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(0, 0, 400, 30);

        jButton1.setText("LOAD PREVIOUS MESSAGES");
        getContentPane().add(jButton1);
        jButton1.setBounds(3, 40, 170, 23);

        jButton2.setText("VIEW ONLINE USER");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(190, 40, 160, 23);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ONLINE"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setResizable(false);
        }

        getContentPane().add(jScrollPane2);
        jScrollPane2.setBounds(400, 70, 100, 500);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed

        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (jButton2.getText().equals("VIEW ONLINE USER")) {
            // jTable1.setVisible(true);
            setSize(500, 600);
            jButton2.setText("HIDE ONLINE USER");
        } else {
            //   jTable1.setVisible(false);
            jButton2.setText("VIEW ONLINE USER");
            setSize(406, 600);
        }

// TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed
    public void run() throws IOException {
        Socket socket = new Socket("127.0.0.1", 9001);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream(), true);
        while (true) {

            String username = "abc";
            //jLabel2.getText().toString();
            String line = in.readLine();
            if (line.startsWith("GETNAME")) {
                out.println(username);
            }
            if (line.startsWith("MESSAGE ")) {
                String msg = line.substring(8);
                jTextArea1.append(msg + "\n");

            }
        }
    }

    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    // public static void main (String[] args) throws IOException{
    public static void main(String[] args) throws IOException {
        ChatClientGuiTEST client = new ChatClientGuiTEST();

       // client.setVisible(true);
        client.run();
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}

ChatServerGui.java

package chating;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;
import java.util.HashSet;
import javax.swing.JOptionPane;

public class ChatServerGui {
    ResultSet rs;

    private static final int PORT = 9001;

    private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();

    public static void main(String[] args) throws Exception {
        System.out.println("The chat server is running.");        
        ServerSocket listener = new ServerSocket(PORT);
        try {
            while (true) {
                new Handler(listener.accept()).start();

            }
        } finally {
            listener.close();
        }

    }

//    public  static void startServer()throws IOException{
//    System.out.println("The chat server is running.");        
//        ServerSocket listener = new ServerSocket(PORT);
//        try {
//            while (true) {
//                new Handler(listener.accept()).start();
//               
//            }
//        } finally {
//            listener.close();
//        }
//    }

    void setVisible(boolean b) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private static class Handler extends Thread {





        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;

        public Handler(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            try {

                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);
                writers.add(out);
                while (true) {
                    out.println("GETNAME");
                    String name = in.readLine();

                    String input = in.readLine();
                    if (input == null) {
                      return;
                    }
                    try{
                        connection obj = new connection();
                    String query="INSERT INTO tb_msg (msg) VALUES('"+input+"')";
                    connection.pst = connection.con.prepareStatement(query);
                    int rst = connection.pst.executeUpdate();

                    }
                    catch(Exception e){
                        JOptionPane.showMessageDialog(null,"ERROR THERE MIGHT BE PROBLEM IN DATABASE","ERROR",0);
                    }
                    for (PrintWriter writer : writers) {
                        writer.println("MESSAGE "+name +":"+ input);
                    }

                }
            } catch (IOException e) {
                System.out.println(e);
            } 
//            finally {
//                
//                if (out != null) {
//                    writers.remove(out);
//                }
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
    }
//}

我在这里大胆猜测。 在服务器文件中,您在while true循环中创建了大量线程。 由于它们是分离的线程,因此主线程的执行不会停止,因此您基本上是在填充JVM内存。

while (true) {
    new Handler(listener.accept()).start();
}

您没有收到OOM错误的原因是因为线程在启动时就结束了,原因是:

while (true) {
    out.println("GETNAME");
    String name = in.readLine();

    String input = in.readLine();
    if (input == null) {
        return; // <-- Ends the while loop and the run function, thread dies
    }

// ...

您应该使用continue而不是return来跳过其余的循环代码。 但是,如果这样做,您的JVM将立即爆炸! 您真的需要大量的Handler吗?

还有一些connectionPreparedStatement实例未正确关闭,我不确定每次收到消息时都创建新的连接是可行的方法。

  相关解决方案