Hi Everyone,

I'm making a Java chat application, but it freezes whenever I click "Connect." My code is attached below. Thanks.

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

public class CinnaChat extends JFrame
{

  JLabel lblServerIP = new JLabel("Server IP:");
  JTextField serverIP = new JTextField(15);

  JLabel lblPort = new JLabel("Port Num:");
  JTextField port = new JTextField(15);

  JLabel lblName = new JLabel("NickName:");
  JTextField name = new JTextField(15);

  JRadioButton serverBTN = new JRadioButton("Server (Host)");
  JRadioButton clientBTN = new JRadioButton("Client (Guest)");

  JButton connect = new JButton("Connect");
  JButton disconnect = new JButton("Disconnect");

  JTextArea messages = new JTextArea("",10,21);
  JTextField mssg = new JTextField(15);
  JButton send = new JButton("Send");

  Font btn = new Font("times new roman",Font.BOLD,20);

  Socket skt = null;
  Socket skt2 = null;
  ServerSocket srvr = null;

  boolean server = true;

  public CinnaChat()
  {
    super("CinnaChat");
    setSize(500,250);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    Container contentArea = getContentPane();
    contentArea.setBackground(Color.lightGray);

    GridLayout flowManager = new GridLayout(1,2);
    contentArea.setLayout(flowManager);

    JPanel pnl = new JPanel();
    pnl.add(lblServerIP);
    pnl.add(serverIP);
    pnl.add(lblPort);
    pnl.add(port);
    pnl.add(lblName);
    pnl.add(name);
    ButtonGroup type = new ButtonGroup();
    type.add(serverBTN);
    serverBTN.addActionListener(
        new ActionListener()
        {
          public void actionPerformed(ActionEvent event)
          {
            server = true;
          }
        }
    );
    type.add(clientBTN);
    clientBTN.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            server = false;
          }
        }
    );
    pnl.add(serverBTN);
    pnl.add(clientBTN);
    pnl.add(connect);
    connect.addActionListener(
        new ActionListener()
        {
          public void actionPerformed(ActionEvent event)
          {
            connect();
          }
        }
    );
    connect.setFont(btn);
    pnl.add(disconnect);
    disconnect.addActionListener(
        new ActionListener()
        {
          public void actionPerformed(ActionEvent event)
          {
            disconnect();
          }
        }
    );

    disconnect.setFont(btn);
    contentArea.add(pnl);

    JPanel pnl2 = new JPanel();
    pnl2.add(new JScrollPane(messages,
                             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    pnl2.add(mssg);
    pnl2.add(send);
    send.addActionListener(
        new ActionListener()
        {
          public void actionPerformed(ActionEvent event)
          {
            send();
          }
        }
    );

    contentArea.add(pnl2);

    setContentPane(contentArea);
  }

  public void connect()
  {
    try
    {
      if(server)
      {
        int portNum = Integer.parseInt(port.getText());
        srvr = new ServerSocket(portNum);
        skt = srvr.accept();
        messages.append("\nServer, "+name.getText()+", has connected.\n\n");
        BufferedReader in = new BufferedReader(new
            InputStreamReader(skt.getInputStream()));
        while (!in.ready()) {}
        messages.append(in.readLine()+"\n");
        in.close();

        skt.close();
        srvr.close();
      }
      else
      {
        int portNum = Integer.parseInt(port.getText());
        skt2 = new Socket(serverIP.getText(), portNum);
        BufferedReader in = new BufferedReader(new
            InputStreamReader(skt2.getInputStream()));
        while (!in.ready()) {}
        messages.append(in.readLine()+"\n");
        in.close();

      }
    }
    catch(Exception e1)
    {
      JOptionPane.showMessageDialog(null, "Error: Connection failed.\n"+
                                    "Please retry.  Check IP Adress\n"+
                                    "and the port number.", "Error",
                                    JOptionPane.ERROR_MESSAGE);
    }
  }

  public void disconnect()
  {
    try{
      skt.close();
      skt2.close();
      srvr.close();
    }
    catch(Exception e2)
    {
    }
  }

  public void send()
  {
    try
    {
      if(server)
      {
        PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
        messages.append(name.getText() + ":  " + mssg.getText() + "\n");
        out.print(name.getText() + ":  " + mssg.getText() + "\n");
        out.close();
      }
      else
      {
        PrintWriter out = new PrintWriter(skt2.getOutputStream(), true);
        messages.append(name.getText() + ":  " + mssg.getText() + "\n");
        out.print(name.getText() + ":  " + mssg.getText() + "\n");
        out.close();
      }
    }
    catch(Exception e3)
    {
    }
  }

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

Recommended Answers

All 7 Replies

if anybody has any advice, I would appreciate it.

You got a lot to learn about multithreading and network programming I see.
Your server can accept only a single connection, ever.
Your client waits forever for input and as soon as it gets anything closes the stream.

thanks, jwenting! so basically, i have to open and close the socket for every message? Thanks. I also updated my code. The server side works, but when I try to get the client working, it freezes up. Thanks.

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

public class CinnaChat extends JFrame
{

  JLabel lblServerIP = new JLabel("Server IP:");
  JTextField serverIP = new JTextField(15);

  JLabel lblPort = new JLabel("Port Num:");
  JTextField port = new JTextField(15);

  JLabel lblName = new JLabel("NickName:");
  JTextField name = new JTextField(15);

  JRadioButton serverBTN = new JRadioButton("Server (Host)");
  JRadioButton clientBTN = new JRadioButton("Client (Guest)");

  JButton connect = new JButton("Connect");
  JButton disconnect = new JButton("Disconnect");

  JTextArea messages = new JTextArea("",10,21);
  JTextField mssg = new JTextField(15);
  JButton send = new JButton("Send");

  JLabel lbl = new JLabel("CinnaChat");

  Font btn = new Font("times new roman",Font.BOLD,20);
  Font lblFont = new Font("times new roman",Font.BOLD+Font.HANGING_BASELINE,45);

  Socket socket = null;
  Socket socket2 = null;
  ServerSocket serverSocket = null;
  PrintWriter out = null;
  BufferedReader in = null;
  PrintWriter out2 = null;
  BufferedReader in2 = null;

  boolean server = true;

  Color purple = new Color(108,111,206);
  Color yellow = new Color(173,115,5);
  Color blue = new Color(15,11,102);

  public CinnaChat()
  {
    super("CinnaChat");
    setSize(505,250);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    Container contentArea = getContentPane();

    GridLayout flowManager = new GridLayout(1,2);
    contentArea.setLayout(flowManager);

    Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
    setCursor(cursor);

    JPanel pnl = new JPanel();
    pnl.add(lbl);
    lbl.setFont(lblFont);
    lbl.setForeground(Color.darkGray);
    pnl.add(lblServerIP);
    lblServerIP.setForeground(purple);
    pnl.add(serverIP);
    pnl.add(lblPort);
    lblPort.setForeground(purple);
    pnl.add(port);
    pnl.add(lblName);
    lblName.setForeground(purple);
    pnl.add(name);
    ButtonGroup type = new ButtonGroup();
    type.add(serverBTN);
    serverBTN.setForeground(yellow);
    serverBTN.addActionListener(
        new ActionListener()
        {
          public void actionPerformed(ActionEvent event)
          {
            server = true;
          }
        }
    );
    type.add(clientBTN);
    clientBTN.setForeground(yellow);
    clientBTN.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            server = false;
          }
        }
    );
    pnl.add(serverBTN);
    pnl.add(clientBTN);
    pnl.add(connect);
    connect.addActionListener(
        new ActionListener()
        {
          public void actionPerformed(ActionEvent event)
          {
            connect();
          }
        }
    );
    connect.setFont(btn);
    connect.setForeground(blue);
    pnl.add(disconnect);
    disconnect.setEnabled(false);
    disconnect.addActionListener(
        new ActionListener()
        {
          public void actionPerformed(ActionEvent event)
          {
            disconnect();
          }
        }
    );
    disconnect.setFont(btn);
    disconnect.setForeground(blue);
    contentArea.add(pnl);

    JPanel pnl2 = new JPanel();
    pnl2.add(new JScrollPane(messages,
                             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
    messages.setEditable(false);
    messages.setCursor(new Cursor(Cursor.TEXT_CURSOR));
    pnl2.add(mssg);
    pnl2.add(send);
    send.setEnabled(false);
    send.addActionListener(
        new ActionListener()
        {
          public void actionPerformed(ActionEvent event)
          {
            send();
          }
        }
    );

    contentArea.add(pnl2);

    contentArea.setBackground(Color.white);

    setContentPane(contentArea);
  }

  public void connect()
  {
    serverBTN.setEnabled(false);
    clientBTN.setEnabled(false);
    disconnect.setEnabled(true);
    connect.setEnabled(false);
    send.setEnabled(true);
    try
    {

      if(!server)
      {
        try
        {
          socket = new Socket(serverIP.getText(),
                              Integer.parseInt(port.getText()));
          out = new PrintWriter(socket.getOutputStream(), true);
          in = new BufferedReader(new InputStreamReader(
              socket.getInputStream()));
          messages.append(in.readLine());
        }
        catch (Exception hostEx)
        {
          JOptionPane.showMessageDialog(null,"Error with port number or IP "+
                                        "Address.","Error",
                                        JOptionPane.ERROR_MESSAGE);
        }

      }
      else
      {
        try
        {
          serverSocket = new ServerSocket(Integer.parseInt(port.getText()));
        }
        catch (Exception portInUseEx)
        {
          JOptionPane.showMessageDialog(null,"Port in use.  Select a different "+
                                        "port.","Port in Use",
                                        JOptionPane.ERROR_MESSAGE);
        }
        PrintWriter out2 = new PrintWriter(
                      socket2.getOutputStream(), true);
        BufferedReader in2 = new BufferedReader(
                        new InputStreamReader(
                            socket2.getInputStream()));
        messages.append(in2.readLine());
      }

    }
    catch (Exception exception)
    {

    }
  }

  public void disconnect()
  {
    serverBTN.setEnabled(true);
    clientBTN.setEnabled(true);
    disconnect.setEnabled(false);
    connect.setEnabled(true);
    send.setEnabled(false);
    try
    {
      if(!server)
      {
        out.close();
        in.close();
        socket.close();
      }
      else
      {
        out2.close();
        in2.close();
        socket2.close();
        serverSocket.close();
      }
    }
    catch(Exception closeEx)
    {
    }
  }

  public void send()
  {
    try
    {
      if(!server)
      {
        messages.append(name.getText() + ":  " + mssg.getText() + "\n");
        out.println(name.getText() + ":  " + mssg.getText());
      }
      else
      {
        messages.append(name.getText() + ":  " + mssg.getText() + "\n");
        out2.println(name.getText() + ":  " + mssg.getText());
      }
    }
    catch(Exception e3)
    {
    }
  }

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

Hi everyone,

basically, i have to open and close the socket for every message

Ghost, you really have to read the API docs. Once you diconnect a socket you cannot reconnect it and in your case your socket is a global one thus the socket does not work properly.

For the rest of my answer i have already answered it at this thread

http://wizardsolutionsusa.com/programmingforums/viewtopic.php?t=10

Richard West

Would not making it global and passing it through functions help?

Thanks.

Take Sun course SL-275. It builds something like what you're trying to do as its final project.
Course takes a week, that phase takes about half a day.

Hi everyone,

Ghost if you really want to build your own chat application using sockets then check the below thread it comes with full source code and explanations

http://wizardsolutionsusa.com/programmingforums/viewtopic.php?t=55

If you have any comments post at the above link. You don't have to be a member to post at the above link. Youy can post as a guest

Thank You

Yours Sincerely

Richard West

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.