-2

I'm new in Java. I'm trying to make a simple chat application, with one client, but something isn't right.. cant figure it out. It gets stuck at connection (right after it) to server when trying to listen to it. Idea is simple: client sends a message, server receives it and sends it back. Please help...!

Main:

public class main {
 public static void main(String[] args) {
    Server Server = new Server();
    Server.runServer();        

    Client client = new Client();
    client.runForm();
}  
}

Server

public class Server {

public static int SERVERA_PORTS = 5432;
private static JTextArea txtMessages;
public static void main(String[] args) {

}

 public void runServer() {   
    //Form
    JFrame frame = new JFrame();
    txtMessages = new JTextArea();
    JPanel pnlContent = (JPanel) frame.getContentPane();
    pnlContent.setLayout(new BorderLayout());
    pnlContent.add(txtMessages, BorderLayout.CENTER);
    txtMessages.setEditable(false);
    frame.setSize(500, 400);
    frame.setLocation(100, 100);
    frame.setTitle("Console");
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setVisible(true);        
    txtMessages.append("Listening!\n*************************\n");

    ServerSocket serverSocket = null;
    try{
            serverSocket = new ServerSocket(SERVERA_PORTS);
    } catch (IOException ex){

            return;
    }

    while(true){
        Socket socket = null;
        try{
            socket = serverSocket.accept();
            System.out.println("Client: "+socket.getRemoteSocketAddress()+" connected");                        
            InputStreamReader IntputaReaders = new InputStreamReader(socket.getInputStream());
            BufferedReader BuferaReaders = new BufferedReader(IntputaReaders);

            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = new Date();                             
            String msg = BuferaReaders.readLine();
            System.out.println(dateFormat.format(date)+": "+msg);   

            //Sends back to clint
            PrintStream PrintStrims = new PrintStream(socket.getOutputStream());
            if(!"".equals(msg)) {
                PrintStrims.println(dateFormat.format(date)+": "+msg);
            }   

            //Puts in GUI
            txtMessages.append(socket.getRemoteSocketAddress()+": "+msg+"\n");



        } catch (IOException ex){
        } finally {
                try{
                        socket.close();
                } catch (Exception ex){}
        }
    }
}

}

Client

public class Client extends JFrame implements ActionListener {

private static JButton btnSend;
private static JButton btnConnect;
private static JTextArea txtMessages;
private static JTextField txtCurrentMessage;
private static JTextField txtServerPort;
private static JTextField txtServerName;

String hosts = "";
int ports;
Socket clientSocket = null;
BufferedReader in = null;

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

}    

private void listen() {
    try {
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String msgIn;
        while ((msgIn = in.readLine()) != null) {
            System.out.println(msgIn);
            txtMessages.append(msgIn+"\n");
        }        
    }catch (IOException ez) {

    }
}


public void connect(){        
      hosts = txtServerName.getText();        
      String strPort = txtServerPort.getText();
      ports = Integer.valueOf(strPort);                

    try{   
      //Ja pieslēdzas
      clientSocket = new Socket(hosts, ports);
      btnSend.setEnabled(true);
      txtMessages.append("U R connected!\n**************\n");
      btnConnect.setEnabled(false); 
      txtCurrentMessage.setEnabled(true);  

    } catch (IOException ex){
        txtMessages.append("Cannot connect.. \n");
    }    
}

public void send(){
    try{
        PrintStream PrintStrims = new PrintStream(clientSocket.getOutputStream());      
        String message = txtCurrentMessage.getText();
        PrintStrims.println(message);
        System.out.println(message); 

    } catch (IOException ex){
    }       
}

public void runForm() {
    JFrame frame = new JFrame();
    txtServerName = new JTextField();
    txtServerName.setPreferredSize(new Dimension(150, 21));
    txtServerPort = new JTextField();
    txtServerPort.setPreferredSize(new Dimension(50, 21));
    txtMessages = new JTextArea();
    txtCurrentMessage = new JTextField();
    txtCurrentMessage.setPreferredSize(new Dimension(350,21));
    btnConnect = new JButton("Connect");
    btnConnect.addActionListener(this);
    btnSend = new JButton("Send");
    btnSend.addActionListener(this);
    JPanel pnlTop = new JPanel(new FlowLayout());
    JPanel pnlBottom = new JPanel(new FlowLayout());
    pnlTop.add(txtServerName);
    pnlTop.add(txtServerPort);
    pnlTop.add(btnConnect);
    pnlBottom.add(txtCurrentMessage);
    pnlBottom.add(btnSend);
    JPanel pnlContent = (JPanel) frame.getContentPane();
    pnlContent.setLayout(new BorderLayout());
    pnlContent.add(pnlTop, BorderLayout.NORTH);
    pnlContent.add(txtMessages, BorderLayout.CENTER);
    pnlContent.add(pnlBottom, BorderLayout.SOUTH);
    frame.setLayout(new BorderLayout());
    frame.add(pnlTop, BorderLayout.NORTH);
    frame.add(txtMessages, BorderLayout.CENTER);
    frame.add(pnlBottom, BorderLayout.SOUTH);
    frame.setSize(500, 400);
    frame.setLocation(100, 100);
    frame.setTitle("Ne pārāk labs čats");
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    txtServerName.setText("127.0.0.1");
    txtServerPort.setText("5432");      
    btnSend.setEnabled(false);
    txtCurrentMessage.setEnabled(false);
    txtMessages.setEditable(false);
    frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == btnSend) {  
        if(!"".equals(txtCurrentMessage.getText()))
        {
            send();          
            txtCurrentMessage.setText("");
        }
    }

    if (e.getSource() == btnConnect) {               
            connect();
            listen();

    }        
}
}
Guy
  • 3
  • 1
  • 3
  • What doesn't work, server or client? – Mordechai Nov 23 '12 at 03:35
  • does keeping the `PrintStrims` variable global, w/o recreate each time a message is sent, help? – Mordechai Nov 23 '12 at 03:52
  • Just putting code and no details about what issue you are facing attracts downvotes – Siddharth Nov 23 '12 at 04:07
  • So much code to debug, and no mention of the issue you are facing. Its like sharing the entire code base and saying "I have a problem, u figure out what it is, where it is, fix it and also since you have all the time in the world also submit my assignment". – Siddharth Nov 23 '12 at 04:36

2 Answers2

0

For chat server and client, I would like to suggest to use OpenFire server and Smack API. Here is a good reference for Smack example. Download OpenFire server.

Zaw Than oo
  • 9,651
  • 13
  • 83
  • 131
0

it would be helpful to know if your server is getting anything from the client after being connected. that way we could determine if the server is not getting a message to send back or if the client is not receiving the return message.

This oracle tutorial may be of help to you as it looks like it uses a gui and does a really good job of explaining how both the client and server work with code. http://www.oracle.com/technetwork/java/socket-140484.html

conversely there could be something wrong with the logic in

if(!"".equals(msg)) {
     PrintStrims.println(dateFormat.format(date)+": "+msg);
}

you may want to make sure that you can actually get into that statement

Moro
  • 49
  • 3