Click here to Skip to main content
15,920,596 members
Home / Discussions / Java
   

Java

 
Question[ASK] about create file in directori Pin
kellyyy6-Mar-11 8:01
kellyyy6-Mar-11 8:01 
AnswerRe: [ASK] about create file in directori Pin
DaveAuld6-Mar-11 8:31
professionalDaveAuld6-Mar-11 8:31 
GeneralRe: [ASK] about create file in directori Pin
kellyyy8-Mar-11 5:27
kellyyy8-Mar-11 5:27 
GeneralRe: [ASK] about create file in directori Pin
TorstenH.9-Mar-11 4:32
TorstenH.9-Mar-11 4:32 
AnswerRe: [ASK] about create file in directori Pin
musefan7-Mar-11 0:13
musefan7-Mar-11 0:13 
GeneralRe: [ASK] about create file in directori Pin
kellyyy8-Mar-11 6:19
kellyyy8-Mar-11 6:19 
GeneralRe: [ASK] about create file in directori Pin
TorstenH.9-Mar-11 4:31
TorstenH.9-Mar-11 4:31 
QuestionTCP Socket Chat-Receive msg on JTextArea Pin
Ireland.ir6-Mar-11 6:38
Ireland.ir6-Mar-11 6:38 
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)
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
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);


        while((to = userInput.readLine()) != null){
                 userOutput.print(to);
                 System.out.println(to);
            }

            userOutput.close();
            userInput.close();
            connectionSocket.close();
        }catch(IOException e){}
    }
}

The bit that I highlighted in bold...I am not sure if tha bit of code is outputting messages sent from a client(A) to a client(B).

--------------------------------------------------------------
Client class --- ChatGUI.java
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!

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...

Many thanks
AnswerRe: TCP Socket Chat-Receive msg on JTextArea Pin
Richard MacCutchan6-Mar-11 22:39
mveRichard MacCutchan6-Mar-11 22:39 
GeneralRe: TCP Socket Chat-Receive msg on JTextArea Pin
Ireland.ir7-Mar-11 1:47
Ireland.ir7-Mar-11 1:47 
QuestionHow to get sound from other apps? [modified] Pin
mk_45-Mar-11 13:13
mk_45-Mar-11 13:13 
Questionnoob question on new Pin
Budlee4-Mar-11 7:56
Budlee4-Mar-11 7:56 
AnswerRe: noob question on new Pin
exiles.prx_ac4-Mar-11 15:49
exiles.prx_ac4-Mar-11 15:49 
GeneralRe: noob question on new Pin
Albert Holguin5-Mar-11 18:39
professionalAlbert Holguin5-Mar-11 18:39 
GeneralRe: noob question on new Pin
jschell7-Mar-11 8:54
jschell7-Mar-11 8:54 
GeneralRe: noob question on new Pin
Albert Holguin7-Mar-11 10:08
professionalAlbert Holguin7-Mar-11 10:08 
GeneralRe: noob question on new Pin
Yadav Akash21-Mar-11 2:31
Yadav Akash21-Mar-11 2:31 
AnswerRe: noob question on new Pin
jschell5-Mar-11 8:25
jschell5-Mar-11 8:25 
QuestionList Interfaces Name Of Cisco Router With SNMP [modified] Pin
navidnmc2-Mar-11 20:49
navidnmc2-Mar-11 20:49 
AnswerRe: List Interfaces Name Of Cisco Router With SNMP Pin
Richard MacCutchan2-Mar-11 23:21
mveRichard MacCutchan2-Mar-11 23:21 
QuestionSun certified java Pin
shamarh1-Mar-11 18:50
shamarh1-Mar-11 18:50 
AnswerRe: Sun certified java Pin
Richard MacCutchan1-Mar-11 21:54
mveRichard MacCutchan1-Mar-11 21:54 
AnswerRe: Sun certified java Pin
David Skelly1-Mar-11 22:20
David Skelly1-Mar-11 22:20 
AnswerRe: Sun certified java Pin
RaviRanjanKr10-Mar-11 16:47
professionalRaviRanjanKr10-Mar-11 16:47 
Questionproblems setting jquery dialog left and top position Pin
CrafterIt1-Mar-11 1:11
CrafterIt1-Mar-11 1:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.