Results 1 to 2 of 2
  1. #1
    sQu3aKy is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

    Question TCP Socket Chat-Receive msg on JTextArea

    Hi to everyone,

    I have three classes: Server, ThreadHandler and Client...so far I am able to connect two clients (tried only two so far as that is all i need) to the server and if i type a message in the text field am able to see the "OUTGOING msg" displayed on the text Area...but No "INCOMING msg"...and I've tried searching and couldn't find a solution please note this is for my project and I am asking for a help with solving this problem and here are the codes for each class:

    ----------------------------------------------------------------
    Server Class = LanChatGUI.java (I left out the generated code and the imports)

    Java Code:
    public class LanChatGUI extends javax.swing.JFrame{
    
       public static ServerSocket serverSocket = null;
       public static boolean listen =  true;
    
        /** Creates new form LanChatGUI */
        public LanChatGUI() {
            initComponents();
        }
    
    
    /**
        * @param args the command line arguments
        */
        public static void main(String args[]) throws IOException {
            new LanChatGUI().setVisible(true);
    
            try{
                serverSocket = new ServerSocket(7777);
                errorLabel.setText(" Waiting connection on port 7777");
            }catch(IOException ex){
                errorLabel.setText("Listening on port 7777 failed!");
                System.exit(-1);
            }
            while(listen){
                new ThreadHandler(serverSocket.accept()).start();
                errorLabel.setText(" LocalMessenger client connected on: "
                        + serverSocket.getInetAddress() + serverSocket.getLocalPort());
            }
        }
    
       // Variables declaration - do not modify                     
        private javax.swing.JPanel backPanel;
        private javax.swing.JLabel bottomLabel;
        public static javax.swing.JButton connectButton;
        public static javax.swing.JLabel errorLabel;
        private javax.swing.JLabel hostlable;
        public static javax.swing.JTextField hosttxt;
        private javax.swing.JLabel portlabel;
        public static javax.swing.JTextField porttxt;
        public static javax.swing.JComboBox selectionBox;
        private javax.swing.JLabel titleLabel;
        // End of variables declaration

    ThreadHandler.java

    Java Code:
    public class ThreadHandler extends Thread {
    
        private Socket connectionSocket = null;
    
        public ThreadHandler(Socket connectionSocket) {
    	super("ThreadHandler");
            this.connectionSocket = connectionSocket;
        }
    
        @Override
        public void run() {
            String to;
            BufferedReader userInput = null;
            PrintWriter userOutput = null;
    
    	try {
                userInput = new BufferedReader(new InputStreamReader(
                        connectionSocket.getInputStream()));
    	    userOutput = new PrintWriter(connectionSocket.getOutputStream(), true);
    
    
            [COLOR="Red"]while((to = userInput.readLine()) != null){
                     userOutput.print(to);
                     System.out.println(to);
                }[/COLOR]
    
                userOutput.close();
                userInput.close();
                connectionSocket.close();
            }catch(IOException e){}
        }
    }
    The bit that I highlighted with red colour...I am not sure if tha bit of code is outputting messages send from a client(s) to other client(s).

    --------------------------------------------------------------
    Client class --- ChatGUI.java

    Java Code:
    public class ChatGUI extends javax.swing.JFrame implements Runnable {
    
        public static Socket connectionSocket = null;
        public static BufferedReader userInput = null;
        public static PrintWriter userOutput = null;
    
        public static StringBuffer toAppend = new StringBuffer("");
        public static StringBuffer toSend = new StringBuffer("");
    
        public static String ipAdd = "127.0.0.1";
        public static int portNum = 7777;
    
        /** Creates new form ChatGUI */
        public ChatGUI() {
            initComponents();
            convtxtField.addActionListener(new ActionAdapter() {
                        public void actionPerformed(ActionEvent e) {
                            String s = convtxtField.getText();
                               if (!s.equals("")) {
                                    appendToChatBox("OUTGOING: " + s + "\n");
                                    convtxtArea.append(toAppend.toString());
                                    toAppend.setLength(0);
                                    convtxtField.selectAll();
                                    // Send the string
                                    sendString(s);
                        }
                    }
                });
        }
    
    
         // Thread-safe way to append to the chat box
         private static void appendToChatBox(String s) {
          synchronized (toAppend) {
             toAppend.append(s);
          }
        }
    
        // Add text to send-buffer
        private static void sendString(String s) {
          synchronized (toSend) {
             toSend.append(s + "\n");
          }
        }
    
    
       private static void closeConnection() {
    
          try {
             if (connectionSocket != null) {
                connectionSocket.close();
                connectionSocket = null;
             }
          }
          catch (IOException e) { connectionSocket = null; }
    
          try {
             if (userInput != null) {
                userInput.close();
                userInput = null;
             }
          }catch (IOException e){userInput = null;}
    
    
          if (userOutput != null) {
             userOutput.close();
             userOutput = null;
          }
       }
    
    /**
        * @param args the command line arguments
        */
        public static void main(String args[]) throws IOException {
    
            String s;
    
            new ChatGUI().setVisible(true);
    
        while(true){
                try{
    
                    connectionSocket = new Socket(ipAdd, portNum);
                    userInput = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                    userOutput = new PrintWriter(connectionSocket.getOutputStream(),true);
    
                }catch(IOException ex){
                    closeConnection();
                }
    
                try{
                    // Send data
                   if (toSend.length() != 0) {
                      userOutput.print(toSend);
                      userOutput.flush();
                      toSend.setLength(0);
                   }
    
                    // Receive data
                   if (userInput.ready()) {
                      s = userInput.readLine();
                      appendToChatBox("INCOMING: " + s + "\n");
                      convtxtArea.append(toAppend.toString());
                      toAppend.setLength(0);
                    }
                  }catch(IOException ex){
                      closeConnection();
                  }
              }
        }
    
    
        // Variables declaration - do not modify                     
        public static javax.swing.JMenuBar MenuBar;
        public static javax.swing.JPopupMenu.Separator MenuSeparator;
        public static javax.swing.JMenu aboutMenu;
        public static javax.swing.JPanel convPanel;
        public static javax.swing.JTextArea convtxtArea;
        public static javax.swing.JTextField convtxtField;
        public static javax.swing.JMenu exitMenu;
        public static javax.swing.JMenu fileMenu;
        public static javax.swing.JMenu helpMenu;
        public static javax.swing.JMenu logoutMenu;
        public static javax.swing.JScrollPane scrollpaneTextArea;
        // End of variables declaration                   
    
    }
    
       class ActionAdapter implements ActionListener {
        public void actionPerformed(ActionEvent e) {}
    }
    So if I run this program the server runs 1st and waits for a client to request a connection and after the client is connected (in this case 2 clients) i type a simple msg like "Hi" from Client A and i type "hello" in Client B i see in the text Area "Outgoing: Hi" in Client A and "Outgoing: Hello" in Client B...but as mentioned above I also want the Incoming messages to be displayed in the text area which i cant figure out how to call the text area in the client class from the ThreadHandler class or mb ther is a different way of doing it so pls help...

    P.S. to see if these messages are been sent to the server..in the "ThreadHandler class" i entered "System.out.println(s);" the bit coloured in red and in the console it shows messages from both clients...so as said i guess all i am missing is the "Incoming part from the server side"....I would appreciate if any1 could assist me with this!


    Many thanks,

  2. #2
    sQu3aKy is offline Member
    Join Date
    Apr 2010
    Posts
    9
    Rep Power
    0

    Default

    All i need is to see incoming messages in both clients other than that everything is working... pls help as i am suppose to submit this by nxt week

    Thnk u

Similar Threads

  1. Simple Chat Server socket coding issues
    By TheGadgetCat in forum Networking
    Replies: 14
    Last Post: 12-17-2010, 12:54 PM
  2. Replies: 9
    Last Post: 06-16-2010, 03:42 AM
  3. best way to signal a thread that's blocking on a socket receive
    By danieru in forum Threads and Synchronization
    Replies: 5
    Last Post: 09-08-2009, 04:47 PM
  4. Using Socket Programming in RMI to create chat application
    By dhaval.rajput.p in forum New To Java
    Replies: 0
    Last Post: 07-14-2009, 06:37 PM
  5. Replies: 0
    Last Post: 12-02-2008, 10:55 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •