0 Replies - 1450 Views - Last Post: 05 October 2012 - 07:55 AM Rate Topic: -----

#1 ajinkyablaze  Icon User is offline

  • D.I.C Head

Reputation: -7
  • View blog
  • Posts: 68
  • Joined: 11-August 12

Append not working

Posted 05 October 2012 - 07:55 AM

i have a client server program which appears to run fine but take a look at the server class.
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JTextArea;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Owner
 */
public class testservergui extends javax.swing.JFrame{
        ArrayList clientOutputStreams;
        ArrayList<String> onlineUsers = new ArrayList();
         
        
        public class ClientHandler implements Runnable	{
		BufferedReader reader;
		Socket sock;
                PrintWriter client;
                
        public ClientHandler(Socket clientSocket, PrintWriter user) {
		// new inputStreamReader and then add it to a BufferedReader
                        client = user;
			try {
				sock = clientSocket;
				InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
				reader = new BufferedReader(isReader);
			} // end try
			catch (Exception ex) {
				System.out.println("error beginning StreamReader");
			} // end catch

		} // end ClientHandler()

		public void run() {
                        String message;
			String[] data;
                        String connect = "Connect";
                        String disconnect = "Disconnect";
                        String chat = "Chat";

			try {
				while ((message = reader.readLine()) != null) {

		Problem	-------->	ta1.append("Received: " + message + '\n');   <------- Problem
                                        System.out.println("Received: " + message);
					data = message.split("¥");
                                        for (String token:data) {
                                            
                                        //System.out.println(token);
                                        
                                        }
                                        
                                        if (data[2].equals(connect)) {

                                                tellEveryone((data[0] + "¥" + data[1] + "¥" + chat));
                                                userAdd(data[0]);

					} else if (data[2].equals(disconnect)) {

                                            tellEveryone((data[0] + "¥has disconnected." + "¥" + chat));
                                            userRemove(data[0]);

					} else if (data[2].equals(chat)) {

                                            tellEveryone(message);

					} else {
                                            System.out.println("No Conditions were met.");
                                        }


			     } // end while
			} // end try
			catch (Exception ex) {
				System.out.println("lost a connection");
                                clientOutputStreams.remove(client);
			} // end catch
		} // end run()
	}
        public void go() {
		clientOutputStreams = new ArrayList();

		try {
			ServerSocket serverSock = new ServerSocket(5000);

			while (true) {
				// set up the server writer function and then begin at the same
			  	// the listener using the Runnable and Thread
				Socket clientSock = serverSock.accept();
				PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
				clientOutputStreams.add(writer);

				// use a Runnable to start a 'second main method that will run
				// the listener
				Thread listener = new Thread(new testservergui.ClientHandler(clientSock, writer));
				listener.start();
				System.out.println("got a connection");
			} // end while
		} // end try
		catch (Exception ex)
		{
			System.out.println("error making a connection");
		} // end catch

	} // end go()


	public void userAdd (String data) {
                String message;
                String add = "¥ ¥Connect", done = "Server¥ ¥Done";
                onlineUsers.add(data);
                String[] tempList = new String[(onlineUsers.size())];
		onlineUsers.toArray(tempList);
                
                for (String token:tempList) {
                    
                    message = (token + add);
                    tellEveryone(message);
                }
                tellEveryone(done);
	}

	public void userRemove (String data) {
                String message;
                String add = "¥ ¥Connect", done = "Server¥ ¥Done";
                onlineUsers.remove(data);
                String[] tempList = new String[(onlineUsers.size())];
		onlineUsers.toArray(tempList);

                for (String token:tempList) {

                    message = (token + add);
                    tellEveryone(message);
                }
                tellEveryone(done);
	}

        public void tellEveryone(String message) {
	// sends message to everyone connected to server
		Iterator it = clientOutputStreams.iterator();

		while (it.hasNext()) {
			try {
				PrintWriter writer = (PrintWriter) it.next();
				writer.println(message);
				//System.out.println("Sending" + message);
                                writer.flush();
			} // end try
			catch (Exception ex) {
				System.out.println("error telling everyone");
			} // end catch
		} // end while
	}
        
        /**
     * Creates new form testservergui
     */
    public testservergui() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        ta1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        ta1.setEditable(false);
        ta1.setColumns(20);
        ta1.setRows(5);
        jScrollPane2.setViewportView(ta1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 364, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    
    public static void main(String args[]) throws Exception{
        
        
                //ts.runn();
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(testservergui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(testservergui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(testservergui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(testservergui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new testservergui().setVisible(true);
            }
        });
       new testservergui().go();
    }
    
    
        

    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea ta1;
    // End of variables declaration
}



search for the problem i highlighted in the above code.
when i execute the code the system.out.println println 'received and then the message'
but the ta1.append does not append the string in the text area ? this is weird.. any help ?

Is This A Good Question/Topic? 0
  • +

Page 1 of 1