Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   Chat client and server, save messages and delete (http://www.go4expert.com/forums/chat-client-server-save-messages-delete-t16974/)

pjpro 19Apr2009 17:54

Chat client and server, save messages and delete
 
I have tried to make a chat application that only saves the recieved messages which can then be deleted. I'm having some major problems with it.

Can anyone please point out or correct my coding. I have tried for ages to get this working but with no joy.

Client Code
Code:

import java.awt.*;
import java.awt.event.*;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.*;
import javax.swing.event.*;

public class Client extends JPanel
                      implements ListSelectionListener {
    private JList save;
    private DefaultListModel saveList;

    private static final String sendString = "Send";
    private static final String deleteString = "Delete";
    private JButton deleteBtn;
    private JTextField enterMsg; 
    private static InetAddress host;
    ObjectOutputStream output;
    ObjectInputStream input;
    String message = "";
   

    public Client() {
        super(new BorderLayout());

        saveList = new DefaultListModel();
        saveList.addElement("Hi How are you?");
        saveList.addElement("I'm ok. How are the kids?");
        saveList.addElement("Thats good to hear. I will have to give you a call for a meeting soon.");
       
        //Create the list and put it in a scroll pane.
        save = new JList(saveList);
        save.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        save.setSelectedIndex(0);
        save.addListSelectionListener(this);
        save.setVisibleRowCount(5);
        JScrollPane listScrollPane = new JScrollPane(save);

        JButton sendBtn = new JButton(sendString);
        SendListener sendListener = new SendListener(sendBtn);
        sendBtn.setActionCommand(sendString);
        sendBtn.addActionListener(sendListener);
        sendBtn.setEnabled(false);

        deleteBtn = new JButton(deleteString);
        deleteBtn.setActionCommand(deleteString);
        deleteBtn.addActionListener(new DeleteListener());

        enterMsg = new JTextField(100);
        enterMsg.addActionListener(sendListener);
        enterMsg.getDocument().addDocumentListener(sendListener);
        String name = saveList.getElementAt(
                save.getSelectedIndex()).toString();

        //Create a panel that uses BoxLayout.
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new BoxLayout(buttonPane,
                                          BoxLayout.LINE_AXIS));
        buttonPane.add(deleteBtn);
        buttonPane.add(Box.createHorizontalStrut(5));
        buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
        buttonPane.add(Box.createHorizontalStrut(5));
        buttonPane.add(enterMsg);
        buttonPane.add(sendBtn);
        buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        add(listScrollPane, BorderLayout.CENTER);
        add(buttonPane, BorderLayout.PAGE_END);
       
    }

    class DeleteListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //This method can be called only if
            //there's a valid selection
            //so go ahead and remove whatever's selected.
            int index = save.getSelectedIndex();
            saveList.remove(index);

            int size = saveList.getSize();

            if (size == 0) { //Nobody's left, disable firing.
                deleteBtn.setEnabled(false);

            } else { //Select an index.
                if (index == saveList.getSize()) {
                    //removed item in last position
                    index--;
                }

                save.setSelectedIndex(index);
                save.ensureIndexIsVisible(index);
            }
        }
    }

    //This listener is shared by the text field and the send button.
    class SendListener implements ActionListener, DocumentListener {
        private boolean alreadyEnabled = false;
        private JButton sendBtn;

        public SendListener(JButton button) {
            this.sendBtn = button;
        }

        //Required by ActionListener.
        public void actionPerformed(ActionEvent e) {
            String message = enterMsg.getText();

            //User didn't type in a unique name...
            if (message.equals("") || alreadyInList(message)) {
                Toolkit.getDefaultToolkit().beep();
                enterMsg.requestFocusInWindow();
                enterMsg.selectAll();
                return;
            }

            int index = save.getSelectedIndex(); //get selected index
            if (index == -1) { //no selection, so insert at beginning
                index = 0;
            } else {          //add after the selected item
                index++;
            }

            saveList.insertElementAt(enterMsg.getText(), index);
            //If we just wanted to add to the end, we'd do this:
            //listModel.addElement(employeeName.getText());

            //Reset the text field.
            enterMsg.requestFocusInWindow();
            enterMsg.setText("");

            //Select the new item and make it visible.
            save.setSelectedIndex(index);
            save.ensureIndexIsVisible(index);
        }

        protected boolean alreadyInList(String name) {
            return saveList.contains(name);
        }

        //Required by DocumentListener.
        public void insertUpdate(DocumentEvent e) {
            enableButton();
        }

        //Required by DocumentListener.
        public void removeUpdate(DocumentEvent e) {
            handleEmptyTextField(e);
        }

        //Required by DocumentListener.
        public void changedUpdate(DocumentEvent e) {
            if (!handleEmptyTextField(e)) {
                enableButton();
            }
        }

        private void enableButton() {
            if (!alreadyEnabled) {
                sendBtn.setEnabled(true);
            }
        }

        private boolean handleEmptyTextField(DocumentEvent e) {
            if (e.getDocument().getLength() <= 0) {
                sendBtn.setEnabled(false);
                alreadyEnabled = false;
                return true;
            }
            return false;
        }
    }

    //This method is required by ListSelectionListener.
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() == false) {

            if (save.getSelectedIndex() == -1) {
            //No selection, disable delete button.
                deleteBtn.setEnabled(false);

            } else {
            //Selection, enable the delete button.
                deleteBtn.setEnabled(true);
            }
        }
    }


    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("ListDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ListDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
   
    public void runClient()
    {
      Socket client;

      try {
          // Step 1: Create a Socket to make connection.

          host = InetAddress.getLocalHost();    //...............
          client = new Socket(host, 50000 );

          // Step 2: Get the input and output streams.
          output = new ObjectOutputStream(
                      client.getOutputStream() );
          output.flush();
          input = new ObjectInputStream(
                      client.getInputStream() );

          // Step 3: Process connection.
          enterMsg.setEnabled( true );
          do {
            try {
                message = (String) input.readObject();
               
                enterMsg.setCaretPosition(
                enterMsg.getText().length() );
            }
            catch ( ClassNotFoundException cnfex ) {
            }
           
          } while ( !message.equals( "SERVER>>> TERMINATE" ) );

          // Step 4: Close connection.
          output.close();
          input.close();
          client.close();
      }
      catch ( EOFException eof ) {
          System.out.println( "Server terminated connection" );
      }
      catch ( IOException e ) {
          e.printStackTrace();
      }
    }

    private void sendData( String s )
    {
      try {
          message = s;
          output.writeObject( "CLIENT1>>> " + s );
          output.flush();
      }
      catch ( IOException cnfex ) {

      }

    }

    class FireListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //This method can be called only if
            //there's a valid selection
            //so go ahead and remove whatever's selected.
            int index = save.getSelectedIndex();
            saveList.remove(index);

            int size = saveList.getSize();

            if (size == 0) { //Nobody's left, disable firing.
                deleteBtn.setEnabled(false);

            } else { //Select an index.
                if (index == saveList.getSize()) {
                    //removed item in last position
                    index--;
                }

                save.setSelectedIndex(index);
                save.ensureIndexIsVisible(index);
            }
        }
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Server Code
Code:

import java.awt.*;
import java.awt.event.*;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.*;
import javax.swing.event.*;

public class Server extends JPanel
                      implements ListSelectionListener {
    private JList save;
    private DefaultListModel saveList;

    private static final String sendString = "Send";
    private static final String deleteString = "Delete";
    private JButton deleteBtn;
    private JTextField enterMsg; 
    private static InetAddress host;
    ObjectOutputStream output;
    ObjectInputStream input;
    String message = "";
   

    public Server() {
        super(new BorderLayout());

        saveList = new DefaultListModel();
        saveList.addElement("Hi How are you?");
        saveList.addElement("I'm ok. How are the kids?");
        saveList.addElement("Thats good to hear. I will have to give you a call for a meeting soon.");
       
        //Create the list and put it in a scroll pane.
        save = new JList(saveList);
        save.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        save.setSelectedIndex(0);
        save.addListSelectionListener(this);
        save.setVisibleRowCount(5);
        JScrollPane listScrollPane = new JScrollPane(save);

        JButton sendBtn = new JButton(sendString);
        SendListener sendListener = new SendListener(sendBtn);
        sendBtn.setActionCommand(sendString);
        sendBtn.addActionListener(sendListener);
        sendBtn.setEnabled(false);

        deleteBtn = new JButton(deleteString);
        deleteBtn.setActionCommand(deleteString);
        deleteBtn.addActionListener(new DeleteListener());

        enterMsg = new JTextField(100);
        enterMsg.addActionListener(sendListener);
        enterMsg.getDocument().addDocumentListener(sendListener);
        String name = saveList.getElementAt(
                save.getSelectedIndex()).toString();

        //Create a panel that uses BoxLayout.
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new BoxLayout(buttonPane,
                                          BoxLayout.LINE_AXIS));
        buttonPane.add(deleteBtn);
        buttonPane.add(Box.createHorizontalStrut(5));
        buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
        buttonPane.add(Box.createHorizontalStrut(5));
        buttonPane.add(enterMsg);
        buttonPane.add(sendBtn);
        buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        add(listScrollPane, BorderLayout.CENTER);
        add(buttonPane, BorderLayout.PAGE_END);
       
    }

    class DeleteListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //This method can be called only if
            //there's a valid selection
            //so go ahead and remove whatever's selected.
            int index = save.getSelectedIndex();
            saveList.remove(index);

            int size = saveList.getSize();

            if (size == 0) { //Nobody's left, disable firing.
                deleteBtn.setEnabled(false);

            } else { //Select an index.
                if (index == saveList.getSize()) {
                    //removed item in last position
                    index--;
                }

                save.setSelectedIndex(index);
                save.ensureIndexIsVisible(index);
            }
        }
    }

    //This listener is shared by the text field and the send button.
    class SendListener implements ActionListener, DocumentListener {
        private boolean alreadyEnabled = false;
        private JButton sendBtn;

        public SendListener(JButton button) {
            this.sendBtn = button;
        }

        //Required by ActionListener.
        public void actionPerformed(ActionEvent e) {
            String message = enterMsg.getText();

            //User didn't type in a unique name...
            if (message.equals("") || alreadyInList(message)) {
                Toolkit.getDefaultToolkit().beep();
                enterMsg.requestFocusInWindow();
                enterMsg.selectAll();
                return;
            }

            int index = save.getSelectedIndex(); //get selected index
            if (index == -1) { //no selection, so insert at beginning
                index = 0;
            } else {          //add after the selected item
                index++;
            }

            saveList.insertElementAt(enterMsg.getText(), index);
            //If we just wanted to add to the end, we'd do this:
            //listModel.addElement(employeeName.getText());

            //Reset the text field.
            enterMsg.requestFocusInWindow();
            enterMsg.setText("");

            //Select the new item and make it visible.
            save.setSelectedIndex(index);
            save.ensureIndexIsVisible(index);
        }

        protected boolean alreadyInList(String name) {
            return saveList.contains(name);
        }

        //Required by DocumentListener.
        public void insertUpdate(DocumentEvent e) {
            enableButton();
        }

        //Required by DocumentListener.
        public void removeUpdate(DocumentEvent e) {
            handleEmptyTextField(e);
        }

        //Required by DocumentListener.
        public void changedUpdate(DocumentEvent e) {
            if (!handleEmptyTextField(e)) {
                enableButton();
            }
        }

        private void enableButton() {
            if (!alreadyEnabled) {
                sendBtn.setEnabled(true);
            }
        }

        private boolean handleEmptyTextField(DocumentEvent e) {
            if (e.getDocument().getLength() <= 0) {
                sendBtn.setEnabled(false);
                alreadyEnabled = false;
                return true;
            }
            return false;
        }
    }

    //This method is required by ListSelectionListener.
    public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting() == false) {

            if (save.getSelectedIndex() == -1) {
            //No selection, disable delete button.
                deleteBtn.setEnabled(false);

            } else {
            //Selection, enable the delete button.
                deleteBtn.setEnabled(true);
            }
        }
    }


    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("ListDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ListDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
 
    }
   
    public void runServer()
    {
      ServerSocket server;
      Socket connection;
      int counter = 1;

      try {
          // Step 1: Create a ServerSocket.
          server = new ServerSocket(50000 );

          while ( true ) {
            // Step 2: Wait for a connection.
            display.setText( "Waiting for connection\n" );
            connection = server.accept();

            display.append( "Connection " + counter +
                " received from: " +
                connection.getInetAddress().getHostName() );

            // Step 3: Get input and output streams.
            output = new ObjectOutputStream(
                          connection.getOutputStream() );
            output.flush();
            input = new ObjectInputStream(
                        connection.getInputStream() );
            display.append( "\nGot I/O streams\n" );

            // Step 4: Process connection.
            String message =
                "SERVER>>> Connection successful";
            output.writeObject( message );
            output.flush();
            enter.setEnabled( true );

            do {
                try {
                  message = (String) input.readObject();
                  display.append( "\n" + message );
                  display.setCaretPosition(
                      display.getText().length() );
                }
                catch ( ClassNotFoundException cnfex ) {
                  display.append(
                      "\nUnknown object type received" );
                }
            } while ( !message.equals( "CLIENT>>> TERMINATE" ) );

            // Step 5: Close connection.
            display.append( "\nUser terminated connection" );
            enter.setEnabled( false );
            output.close();
            input.close();
            connection.close();

            ++counter;
          }
      }
      catch ( EOFException eof ) {
          System.out.println( "Client terminated connection" );
      }
      catch ( IOException io ) {
          io.printStackTrace();
      }
    }

    private void sendData( String s )
    {
      try {
          output.writeObject( "CLIENT2>>> " + s );
          output.flush();
          display.append( "\nCLIENT2>>>" + s );
      }
      catch ( IOException cnfex ) {
          display.append(
            "\nError writing object" );
      }
    }

    public static void main( String args[] )
    {
      Server app = new Server();

      app.runServer();
    }
 }//end of Server

Thanks in advance


All times are GMT +5.5. The time now is 11:30.