I was doing GUI based application, when i run the MyChatPage particularly, it able to send the text to the server and send to the client textarea, which is my objective, but if i run from MyChatIP class and create new object to open the MyCHatpage frame, it will hang, and i know is because due to the run() method from MyChatpage that i called

the question is, if i not allowed to call the run()method in MyCHatIP, the what i suppose to do to make it run automatically when open the MyChatPage frame without hang, so i able to send the text

MyChatIP

private void btokActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
        String serveraddress = txtip.getText();
    try {
            Socket socket = new Socket(serveraddress, 1235);
        in = new BufferedReader(new InputStreamReader(
            socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream(), true);

            MyChatPage cp = new MyChatPage();
            cp.setAddress(serveraddress);
            cp.setName2(PassName);
            cp.setEmail2(PassEmail);
            cp.setVisible(true);
            cp.run();
            cp.setLocationRelativeTo(null);
            JOptionPane.showMessageDialog(null, "MyChat Server Connection Success!");
            this.dispose();

    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Connect Fail!");
    }
    }

MyChatPage

public class MyChatPage extends javax.swing.JFrame {

    BufferedReader in2;
    PrintWriter out2;
    private static String PassAddress;
    private static String PassName2;
    private static String PassEmail2;

    /**
     * Creates new form MyChatPage
     */
    public MyChatPage() throws IOException {
        initComponents();

        /**
         * Responds to pressing the enter key in the textfield by sending the
         * contents of the text field to the server. Then clear the text area in
         * preparation for the next message.
         */
    }

public void run() throws IOException {
        Socket socket = new Socket(getAddress(), 1235);
        out2 = new PrintWriter(socket.getOutputStream(), true);
        in2 = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));

        while (true) {
            String line = in2.readLine();
            if (line.startsWith("SUBMITNAME")) {
                out2.println(getName2());
            } else if (line.startsWith("NAMEACCEPTED")) {
                txtmsg.setEditable(true);
            } else if (line.startsWith("MESSAGE")) {
                txtmsgarea.append(line.substring(8) + "\n");
            }
        }
    }

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

        //alternate testing
        MyChatPage mcp = new MyChatPage();
        mcp.setVisible(true);
        mcp.run();
        //JOptionPane.showMessageDialog(null, mcp.out);
    }

Server

public class MyChatServer {

    private static final int PORT = 1235;
    private static HashSet<String> names = new HashSet<String>();
    /**
     * The set of all the print writers for all the clients. This set is kept so
     * we can easily broadcast messages.
     */
    private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();

    /**
     * The application main method, which just listens on a port and spawns
     * handler threads.
     */
    public static void main(String[] args) throws Exception {

        System.out.println("MyChat server is running.");
        ServerSocket listener = new ServerSocket(PORT);

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

    }

    private static class Handler extends Thread {

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

        /**
         * Constructs a handler thread, squirreling away the socket. All the
         * interesting work is done in the run method.
         */
        public Handler(Socket socket) {
            this.socket = socket;
        }

        /**
         * Services this thread's client by repeatedly requesting a screen name
         * until a unique one has been submitted, then acknowledges the name and
         * registers the output stream for the client in a global set, then
         * repeatedly gets inputs and broadcasts them.
         */
        public void run() {
            try {

                // Create character streams for the socket.
                in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                while (true) {
                    out.println("SUBMITNAME");
                    name = in.readLine();
                    if (name == null) {
                        return;
                    }
                    synchronized (names) {
                        if (!names.contains(name)) {
                            names.add(name);
                            break;
                        }
                    }
                }

                out.println("NAMEACCEPTED");
                writers.add(out);

                while (true) {
                    String input = in.readLine();
                    if (input == null) {
                        return;
                    }
                    for (PrintWriter writer : writers) {
                        writer.println("MESSAGE " + name + ": " + input);
                    }
                }

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

        }
    }
}

Correction, i have made the change of

MyChatIP

public void connectserver() throws IOException
{
    String serveraddress = txtip.getText();
     Socket socket = new Socket(serveraddress, 1235);
        in = new BufferedReader(new InputStreamReader(
            socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream(), true);
        MyChatPage cp = new MyChatPage();
            cp.setAddress(serveraddress);
            JOptionPane.showMessageDialog(null, out);
}
    private void btokActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:

    try {
            MyChatPage cp = new MyChatPage();
            //cp.setAddress(serveraddress);
            cp.setName2(PassName);
            cp.setEmail2(PassEmail);
            cp.setVisible(true);
            cp.setLocationRelativeTo(null);
           cp.run();
            JOptionPane.showMessageDialog(null, "MyChat Server Connection Success!");
            this.dispose();

    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Connect Fail!");
    }
    }

MyChatPage

public void run() throws IOException {
        mcp.connectserver();
        //Socket socket2 = new Socket(getAddress(), 1235);
       //out2 = new PrintWriter(socket2.getOutputStream(), true);
       // in2 = new BufferedReader(new InputStreamReader(
          //      socket2.getInputStream()));

        while (true) {
            String line = mcp.in.readLine();
            if (line.startsWith("SUBMITNAME")) {
                mcp.out.println(getName2());
            } else if (line.startsWith("NAMEACCEPTED")) {
                txtmsg.setEditable(true);
            } else if (line.startsWith("MESSAGE")) {
                txtmsgarea.append(line.substring(8) + "\n");
            }
        }
    }



private void btsendmsgActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        mcp.out.println(txtmsg.getText());
        JOptionPane.showMessageDialog(null, txtmsg.getText());
        txtmsg.setText("");
    }

As a guess:

Your run method contains an infinite loop, so if you call it directly it will never return and the calling program will be frozen. So you need to execute it on a different (new) Thread.

(That's why it's called "run" - it implements the Runnable interface that a new Thread needs.)

  • (FileIO, JDBC) Socket are long and hard actions,

  • Swing in single threaded and updates to already visible Swing GUI must be done on Event Dispatch Thread, code from hard and long running events by default never to notify EDT, as you can see in your code, every notification to Swing GUI are never updated, are caled out of EDT,

  • there are two options

    1. by using SwingWoker (isn't reusable, is designated for single event)

    2. output from Workers Thread would be wrapped into invokeLater, not whole methods, just single method (e.g. code line txtmsgarea.append(line.substring(8) + "\n"); should be inside invokeLater)

    3. more about EDT in Oracle trail - Concurency in Swing

Hi, Assalamualaikum wbrt...

commented: Mualaikumsalam. Please avoid reviving old discussions without new ideas or input. +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.