Hi Everyone,

I'm trying to create an instant messaging program, but for some reason the client and server won't connect. My code is below. Thanks in advanced for helping me.

By the way, the client and server program are one in the same. A radio button gives you the option of which to use.

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.lang.*;

/*
 * CIM.java
 *
 */

/**
 *
 * @author  CRD
 */
public class CIM extends JFrame {

    public boolean server = false;
    public String name = "Anonymous";
    public String ipAd = "localhost";
    public String msgs = "";
    ObjectOutputStream out;
    ObjectInputStream in;
    Socket skt;
    ServerSocket srvr;
    public int serverCounter = 1;

    /** Creates new form CIM */
    public CIM() {
        initComponents();
        buttonGroup1.add(jRadioButton1);
        buttonGroup1.add(jRadioButton2);
    }

    public void runServer()
    {

        try
        {

            connection.setBackground(new java.awt.Color(255, 51, 51));
            srvr = new ServerSocket(12345, 50000);
            while(true)
            {
                try
                {
                    waitForServerConnection();
                    getServerStreams();
                    processServerConnection();
                }
                catch(Exception ex2)
                {
                    allMsgs_txtarea.setText("Error Connecting: Please Try Again.");
                }
                finally
                {
                    closeServerConnection();

                }
            }
        }
        catch(Exception ioex)
        {
            allMsgs_txtarea.setText("Error Connecting: Please Try Again.");
        }
    }

    public void waitForServerConnection() throws Exception
    {
        skt = srvr.accept();
        displayMessage( "Connection recieved from: "+skt.getInetAddress().getHostName() );
    }

    public void getServerStreams() throws Exception
    {
        connection.setBackground(new java.awt.Color(255, 255, 51));
        out = new ObjectOutputStream( skt.getOutputStream() );
        out.flush();

        in = new ObjectInputStream(skt.getInputStream());

    }

    private void processServerConnection() throws IOException
    {
        String message = "Connection Successful";
        sendData(message);
        connection.setBackground(new java.awt.Color(51,255,51));
        do
        {
            try
            {
                message = (String) in.readObject();
                displayMessage("\n" + message);
            }
            catch(Exception e)
            {
                displayMessage("\n" + "error...");
            }
        }
        while (!message.equals("CLIENT>>> TERMINATE"));
    }

    private void closeServerConnection()
    {
        displayMessage("\nTerminating connection\n");
        connection.setBackground(new java.awt.Color(255, 51, 51));
        try
        {
            out.close();
            in.close();
            skt.close();
        }
        catch(Exception ee)
        {

        }
    }

    public void sendData(String message)
    {
        try
        {
            if(server)
            {
                out.writeObject("SERVER>>> "+message);
            }
            else if (!server)
            {
                out.writeObject("CLIENT>>> "+message);
            }
            out.flush();
            displayMessage("\n"+name+">>> "+message);
        }
        catch(Exception se)
        {

        }
    }

    public void displayMessage (final String messageToDisplay)
    {
        SwingUtilities.invokeLater(
            new Runnable() {
                public void run()
                {
                    allMsgs_txtarea.append(messageToDisplay);
                    allMsgs_txtarea.setCaretPosition(allMsgs_txtarea.getText().length());
                }
            }
        );
    }

    public void runClient()
    {
        try
        {
            connection.setBackground(new java.awt.Color(255, 51, 51));
            connectToServer();
            getClientStreams();
            processClientConnection();
        }
        catch(Exception CE)
        {

        }
        finally
        {
            closeClientConnection();
        }
    }

    public void connectToServer() throws IOException
    {
        skt = new Socket(ipAd,12345);
    }

    private void getClientStreams() throws IOException
    {
        out = new ObjectOutputStream(skt.getOutputStream());
        out.flush();
        in = new ObjectInputStream(skt.getInputStream());
        connection.setBackground(new java.awt.Color(255, 255, 51));
    }

    public void processClientConnection() throws IOException
    {
        String message = "";
         connection.setBackground(new java.awt.Color(51,255,51));
         do
         {
             try
             {
                 message = (String) in.readObject();
                 displayMessage("\n"+message);
             }
             catch(Exception cnfe)
             {
                 displayMessage("\nERROR.");
             }
         }
         while(!message.equals("SERVER>>> TERMINATE"));
    }

    private void closeClientConnection()
    {
        displayMessage("\nTerminating connection\n");
        connection.setBackground(new java.awt.Color(255, 51, 51));
        try
        {
            out.close();
            in.close();
            skt.close();
        }
        catch(Exception ee)
        {

        }
    }

    public void decide()
    {
        if(server)
        {
            runServer();
        }
        else if (!server)
        {
            runClient();
        }
    }


    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
        panel4 = new java.awt.Panel();
        buttonGroup1 = new javax.swing.ButtonGroup();
        panel1 = new java.awt.Panel();
        panel7 = new java.awt.Panel();
        label3 = new java.awt.Label();
        panel8 = new java.awt.Panel();
        panel9 = new java.awt.Panel();
        label7 = new java.awt.Label();
        connection = new java.awt.Panel();
        jPanel1 = new javax.swing.JPanel();
        label4 = new java.awt.Label();
        name_field = new java.awt.TextField();
        button1 = new java.awt.Button();
        panel10 = new java.awt.Panel();
        label5 = new java.awt.Label();
        panel11 = new java.awt.Panel();
        panel12 = new java.awt.Panel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        panel13 = new java.awt.Panel();
        label6 = new java.awt.Label();
        panel14 = new java.awt.Panel();
        ip = new java.awt.TextField();
        panel2 = new java.awt.Panel();
        panel3 = new java.awt.Panel();
        label1 = new java.awt.Label();
        allMsgs_txtarea = new java.awt.TextArea();
        panel5 = new java.awt.Panel();
        label2 = new java.awt.Label();
        panel6 = new java.awt.Panel();
        send_btn = new java.awt.Button();
        msg_txtarea = new java.awt.TextArea();

        getContentPane().setLayout(new java.awt.GridLayout(1, 2));

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(204, 204, 204));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setFont(new java.awt.Font("Times New Roman", 0, 10));
        panel1.setLayout(new java.awt.GridLayout(2, 1));

        panel1.setBackground(new java.awt.Color(255, 255, 204));
        panel7.setLayout(new java.awt.BorderLayout());

        panel7.setBackground(new java.awt.Color(226, 222, 222));
        label3.setBackground(new java.awt.Color(102, 102, 255));
        label3.setFont(new java.awt.Font("Dialog", 1, 12));
        label3.setText("Simple Settings:");
        panel7.add(label3, java.awt.BorderLayout.NORTH);

        panel8.setLayout(new java.awt.GridLayout(2, 1));

        panel8.setBackground(new java.awt.Color(255, 255, 255));
        panel9.setLayout(new java.awt.BorderLayout());

        label7.setBackground(new java.awt.Color(153, 153, 255));
        label7.setText("Connection Status:");
        panel9.add(label7, java.awt.BorderLayout.NORTH);

        connection.setBackground(new java.awt.Color(255, 51, 51));
        panel9.add(connection, java.awt.BorderLayout.CENTER);

        panel8.add(panel9);

        jPanel1.setBackground(new java.awt.Color(204, 204, 255));
        label4.setAlignment(java.awt.Label.CENTER);
        label4.setText("Name:");
        jPanel1.add(label4);

        name_field.setText("Anonymous");
        name_field.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                name_fieldActionPerformed(evt);
            }
        });

        jPanel1.add(name_field);

        button1.setLabel("Start/Reset Connection");
        button1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button1ActionPerformed(evt);
            }
        });

        jPanel1.add(button1);

        panel8.add(jPanel1);

        panel7.add(panel8, java.awt.BorderLayout.CENTER);

        panel1.add(panel7);

        panel10.setLayout(new java.awt.BorderLayout());

        panel10.setBackground(new java.awt.Color(226, 222, 222));
        label5.setBackground(new java.awt.Color(102, 102, 255));
        label5.setFont(new java.awt.Font("Dialog", 1, 12));
        label5.setText("Advanced Settings");
        panel10.add(label5, java.awt.BorderLayout.NORTH);

        panel11.setLayout(new java.awt.GridLayout(2, 1));

        panel11.setBackground(new java.awt.Color(255, 255, 255));
        panel12.setBackground(new java.awt.Color(204, 204, 255));
        jRadioButton1.setBackground(new java.awt.Color(204, 204, 255));
        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setSelected(true);
        jRadioButton1.setText("Host (Server)    ");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });

        panel12.add(jRadioButton1);

        jRadioButton2.setBackground(new java.awt.Color(204, 204, 255));
        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setText("User (Client)    ");
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton2ActionPerformed(evt);
            }
        });

        panel12.add(jRadioButton2);

        panel11.add(panel12);

        panel13.setLayout(new java.awt.BorderLayout());

        label6.setBackground(new java.awt.Color(153, 153, 255));
        label6.setText("IP:");
        panel13.add(label6, java.awt.BorderLayout.NORTH);

        panel14.setBackground(new java.awt.Color(204, 204, 255));
        ip.setEditable(false);
        ip.setText("localhost");
        ip.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ipActionPerformed(evt);
            }
        });

        panel14.add(ip);

        panel13.add(panel14, java.awt.BorderLayout.CENTER);

        panel11.add(panel13);

        panel10.add(panel11, java.awt.BorderLayout.CENTER);

        panel1.add(panel10);

        getContentPane().add(panel1);

        panel2.setLayout(new java.awt.GridLayout(2, 1));

        panel2.setBackground(new java.awt.Color(217, 212, 212));
        panel3.setLayout(new java.awt.BorderLayout());

        panel3.setBackground(new java.awt.Color(204, 204, 204));
        label1.setFont(new java.awt.Font("Dialog", 1, 12));
        label1.setText("Incoming/Outgoing Messages:");
        panel3.add(label1, java.awt.BorderLayout.NORTH);

        allMsgs_txtarea.setEditable(false);
        panel3.add(allMsgs_txtarea, java.awt.BorderLayout.CENTER);

        panel2.add(panel3);

        panel5.setLayout(new java.awt.BorderLayout());

        panel5.setBackground(new java.awt.Color(204, 204, 204));
        label2.setFont(new java.awt.Font("Dialog", 1, 12));
        label2.setText("Your Outgoing Messages:");
        panel5.add(label2, java.awt.BorderLayout.NORTH);

        panel6.setLayout(new java.awt.BorderLayout());

        send_btn.setBackground(new java.awt.Color(102, 102, 102));
        send_btn.setForeground(new java.awt.Color(255, 255, 255));
        send_btn.setLabel("Send");
        send_btn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                send_btnActionPerformed(evt);
            }
        });

        panel6.add(send_btn, java.awt.BorderLayout.SOUTH);

        panel6.add(msg_txtarea, java.awt.BorderLayout.CENTER);

        panel5.add(panel6, java.awt.BorderLayout.CENTER);

        panel2.add(panel5);

        getContentPane().add(panel2);

        pack();
    }
    // </editor-fold>

    private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
        decide();
    }

    private void send_btnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
        sendData( msg_txtarea.getText() );
        msg_txtarea.setText("");
    }

    private void ipActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
        ipAd = ip.getText();
    }

    private void name_fieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
        name = name_field.getText();
    }

    private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
        server = false;
        ip.setEditable(true);
    }

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
        server = true;
        ip.setEditable(false);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                CIM cim = new CIM();
                cim.setVisible(true);
                cim.setTitle("CIM - Cinnamon Instant Messaging");
            }
        });
    }

    // Variables declaration - do not modify
    private java.awt.TextArea allMsgs_txtarea;
    private java.awt.Button button1;
    private javax.swing.ButtonGroup buttonGroup1;
    private java.awt.Panel connection;
    private java.awt.TextField ip;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private java.awt.Label label1;
    private java.awt.Label label2;
    private java.awt.Label label3;
    private java.awt.Label label4;
    private java.awt.Label label5;
    private java.awt.Label label6;
    private java.awt.Label label7;
    private java.awt.TextArea msg_txtarea;
    private java.awt.TextField name_field;
    private java.awt.Panel panel1;
    private java.awt.Panel panel10;
    private java.awt.Panel panel11;
    private java.awt.Panel panel12;
    private java.awt.Panel panel13;
    private java.awt.Panel panel14;
    private java.awt.Panel panel2;
    private java.awt.Panel panel3;
    private java.awt.Panel panel4;
    private java.awt.Panel panel5;
    private java.awt.Panel panel6;
    private java.awt.Panel panel7;
    private java.awt.Panel panel8;
    private java.awt.Panel panel9;
    private java.awt.Button send_btn;
    // End of variables declaration

}

Can someone PLEASE help?

Thanks.

Ghost,

First a rant, then I will help you and then maybe some more ranting.

You have not been forthcoming with the details of your problem and the things you have tried to solve it thus far. Yet very forthcoming with a large amount of code. This makes it hard for us to help you. I am experienced with using sockets but the approach of your question doesn't inspire me to trawl through your code looking for the problem when you haven't shown much effort in aiding us to assist you. “for some reason the client and server won't connect is not very helpful! Remember you are the one who needs our help. It is your problem not ours! So show a bit more effort when asking for help, to do otherwise is disrespectful of our time. This, I suspect, is why nobody has responded. Read the below article and you will find this situation is fully explained.

http://www.catb.org/~esr/faqs/smart-questions.html

Having said that, I did say I was going to help you. So ....

Change the declaration of the boolean variable 'server' from:

public boolean server = false;

to

public boolean server = true;

As you can see below, the sockets now establish a connection.

Proto  Local Address		  Foreign Address		State
TCP	0.0.0.0:12345		  0.0.0.0:0			  LISTENING
TCP	127.0.0.1:4185		 127.0.0.1:12345		ESTABLISHED
TCP	127.0.0.1:12345		127.0.0.1:4185		 ESTABLISHED

OK, but now tell me WHY that worked! I will give you a clue, the problem is not even socket related, it is a logic flaw.

Your code could really do with just a few system.out.println's .... that is all it took to locate this problem!!!

Again, show a bit more effort in your requests for help or you will not receive assistance like this from me again. Besides when you see how simple this problem is I am sure (again with just a little effort) you could have found this for yourself.

Have Fun,

Kate

Sorry I didn't specify the question and thank you very much for helping me.

The reason it didn't work is because the default value says the server is selected, but my server variable says otherwise.

Thanks again for your help.

Hi,

It seems like it still doesn't work. All the buttons somehow become disabled after I click connect and they both connect.

Any suggestions? Thanks.

All the buttons somehow become disabled after I click connect and they both connect.

I know, I saw this problem myself. But it wasn't what you were asking for help with so I didn't address it, besides I wanted to see how far you could get with this by yourself. If you analyze the problem you will see that the whole interface becomes unresponsive, not just the buttons. Your whole application freezes.

Did you read that article, I suspected not. You have not said anything about what you have tried yourself to locate this problem. Just another 'somehow' something doesn't work statement. Have you put system.out.println's throughout your code to locate the problem?

You probably think I am being hard on you, but I am trying to get you to rely on your own abilities first before calling for help at the first problem. You will find it more satisfying if you locate and resolve the problems for yourself and you will become a more proficient programmer at the same time. If you cannot resolve a particular problem, then fine, post details about the problem and what you have achieved thus far.

Any suggestions?

Admittedly, this one could be a little tricky to the newcomer and easily overlooked. So research the concept of 'blocking' in the InputStream and it's subclasses. 'blocking' is the cause of this.

If you put println's at the beginning and end of each function you will be able to see which function never returns. Then you can use more println's to further narrow down the 'problem' line of code. If you can tell me the line of the code which freezes the application, I will tell you why (if it doesn't become instantly clear).

Kate

Hi,

It seems like it still doesn't work. All the buttons somehow become disabled after I click connect and they both connect.

that should tell you a lot of what's happening.
Ever heard of multithreading? You're going to need it if you don't want your application to just block waiting for network traffic to process (which will never arrive because your application on the other end is also blocking while waiting for input).

Combine that with Kate's excellent advise and you should be on your way to the nearest O'Reilly book dealer to get yourself their excellent Java Threads and Java Network Programming books in the latest editions ;)

Hi Guys,

Sorry I haven't gotten back to you sooner. OK - I used the println function to narrow down the problem. It seems like in the process client/server connections the program freezes. The program never enters the do-while loop.

If I understand JWenting correctly, he is saying that the program is trying to send and recieve messages at the same time, so I need to use threads.

Thanks again for all your help.

Am I doing something wrong or have you guys just not seen this thread?

Your program is not responding because it's locked in a loop waiting for something to happen.
On the other side the exact same thing is happening, preventing that instance from sending a response.

Read up on network programming and multithreading.

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.