# Probleme mit XMLEncoder/XMLDecoder



## sanaline (27. Jun 2011)

Hallo, 

ich benutze XMLEncoder und XMLDecoder um Objekte zwischen 2 Unterschiedliche Virtualmachine zu senden.
Irgendwie funktionniert diese nicht richtig aber ich weiss nicht genau, woran das Problem liegt:

Ergebniss nach Ausführung des Programms: Server waiting for client on port ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=11870]
New client asked for a connection
Starting a thread for a new Client
Thread trying to create Object Input/Output Streams
Thread waiting for a String from the Client
sshsteuerung.Steuerung.Daten@6f7ce9
New client asked for a connection
Starting a thread for a new Client
Thread trying to create Object Input/Output Streams
Thread waiting for a String from the Client


Hier sind die verschiedenen Klassen:

Steuerung.java:

```
package sshsteuerung.Steuerung;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import sshsteuerung.SSHGUIView;

/**
 *
 * @author 
 */
public class Steuerung {
	
    class StartListener implements ActionListener {
    	
        public void actionPerformed(ActionEvent e) 
        {
        	if (m_view.getStatusRadioBtn().isSelected()){
            	Client client = new Client(11870);
        		client.send("ls");
        		Object status = client.read();
        		System.out.println(status.toString());
        		client.closeEncoder();
        		client.closeDecoder();
           
        	} else if (m_view.getSSH2RadioBtn().isSelected()) {
            	Daten t = new Daten();
            	t.setBenutzername(m_view.getBenutzerTxt().getText());
            	t.setPasswort(m_view.getPasswordTxf().getText());
            	t.setServeurname(m_view.TxtSName.getText());
            	t.setPrograme(m_view.TxtArgument.getText());
            	t.setCommandLine(m_view.TxtProgramm.getText());
            	Client client = new Client(11870);
            	client.send(t);
            	client.closeEncoder();
        	}
        }
    }
    
    
        //... The Controller needs to interact with both the Model and View.
    private Daten m_model;
    private SSHGUIView  m_view;
    private SSHConnect connect;
    StatusCronJobs statuscron;
    //========================================================== constructor
    /** Constructor */
    public Steuerung(Daten model, SSHGUIView view) {
        m_model = model;
        m_view  = view;
        statuscron = new StatusCronJobs(m_view);
        //... Add listeners to the view.
        view.addStartExecuteCommandListener(new StartListener());
       // view.addCheckSSH2Listener(new CheckSSH2BoxListener());
       // view.addCheckSSHListener(new CheckSSHBoxListener());
       // view.addServeurNameListener(new ImputServerNameListerner());
       // view.addSteuerProgrammListener(new ImputSteueungProgrammListerner());
       // view.addArgumentListener(new ImputArgumentListerner());
       // view.addBenutzerNameListener(new ImputBenutzerNameListerner());
      //  view.addPasswortListener(new ImputPasswortListerner());
    }
    

    
    
    ////////////////////////////////////////// inner class StartListener
    /** Beim Clicken von Start Button
     *  1. Get the user input number from the View.
     *  2. 
     *  3. Get the result from the Model.
     *  4. Tell the View to display the result.
     * If there was an error, tell the View to display it.
     * 
     */
   	
        	
        	
        	/*m_view.clear();

           // String userInput = m_model.CheckDaten();
           // if(!userInput.isEmpty() &&  m_model.CheckDaten().equals("OK"))
           // {
               // m_view.worker = new SwingWorker<String, Void>(){
                
               // protected String doInBackground() throws Exception{
                try {
                    if(m_model.getConectionType().equals("SSH2"))
                        connect = new SSH2Connection(m_model.getBenutzername(), m_model.getPasswort(),m_model.getServeurname(),m_model.getPort());
                        //connect = SSH2Connect(m_model.getBenutzername(), m_model.getPasswort(),10000,m_model.getServeurname(),m_model.getPort()
                    if(!connect.getTexte().isEmpty())
                     {
                         m_view.showMessage(connect.getTexte());
                         return msgError;
                     }
                  // programme et parametre
                  connect.executeCommand(m_model.getProgramm().trim() + " " +
                          m_model.getCommandLine().trim());
                
                 // StatusCronJobs statuscron = new StatusCronJobs(connect,m_view);
                  if(!statuscron.getStatusRunning())
                  {
                      System.out.println("Threads gestarted");
                      statuscron.setStatusRunning(true);
                      statuscron.start(connect);
                  }
                }
                catch (UnknownHostException serv) {
                	MsgError.add("Servername "+ serv.getMessage()+"  ist nicht richtig, bitte überprüfen Sie und versuchen Sie nochmal!");
                      Logger.getLogger(SSH2Connection.class.getName()).log(Level.SEVERE, null, serv);
                } catch (IOException ie) {
                	Logger.getLogger(SSH2Connection.class.getName()).log(Level.SEVERE, null, ie);
                	MsgError.add(ie.getMessage());
                } catch (SSH2Exception ssh2e) {
                	Logger.getLogger(SSH2Connection.class.getName()).log(Level.SEVERE, null, ssh2e);
                  //strMessage += ex.getMessage();
                	MsgError.add("überprüfen Sie noch Ihre Eingabe bzw. Benutzername und Passwort!");
                	MsgError.add("");
                	MsgError.add(ssh2e.toString());
                } catch (Throwable t) {
                    t.printStackTrace();
                    msgError=t.toString();
                    m_view.showMessage(connect.getTexte());
                }
            	m_view.showMessage(MsgError);
            	MsgError.clear(); // all Error will be clean...
                return "";
                    
                }
                @Override
                protected void done(){
                    if(msgError.isEmpty())
                       m_view.showMessage(connect.getTexte());
                        }
                    };
                // fuehrt den SwingWorker;damit unser Gui nicht hÃ¤ngt
                m_view.worker.execute();

            }
            else if (!userInput.isEmpty())
            {
            	MsgError.add("Einige Eingabe fehlen");
                m_view.showMessage(MsgError);
                m_view.setMarkierung(userInput);
            }
            
        }
    }//end inner class StartListener //connect.executeCommand("ps -C cron");*/
    
    
    class CheckSSHBoxListener implements ActionListener {

         public void actionPerformed(ActionEvent e) {
             
             m_model.setConectionType("Status");
        }
    }// end inner class ClearListener
    
    class CheckSSH2BoxListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
           m_model.setConectionType("SSH2");
            
        }
    }// end inner class ClearListener
    
    class ImputServerNameListerner implements KeyListener {

        public void keyTyped(KeyEvent e) {
            m_model.setServeurname(m_view.TxtSName.getText());
        }

        public void keyPressed(KeyEvent e) {
             m_model.setServeurname(m_view.TxtSName.getText());
        }
        public void keyReleased(KeyEvent e) {
             m_model.setServeurname(m_view.TxtSName.getText());
        }
    }// end inner class ClearListener
    
    class ImputSteueungProgrammListerner implements KeyListener {

        public void keyTyped(KeyEvent e) {
            m_model.setPrograme(m_view.TxtProgramm.getText());
            m_view.clear();
        }

        public void keyPressed(KeyEvent e) {
             m_model.setPrograme(m_view.TxtProgramm.getText());
        }

        public void keyReleased(KeyEvent e) {
             m_model.setPrograme(m_view.TxtProgramm.getText());
        }
    }// end inner class ClearListener
    
    class ImputArgumentListerner implements KeyListener {

        public void keyTyped(KeyEvent e) {
            m_model.setCommandLine(m_view.TxtArgument.getText());
        }

        public void keyPressed(KeyEvent e) {
             m_model.setCommandLine(m_view.TxtArgument.getText());
        }

        public void keyReleased(KeyEvent e) {
             m_model.setCommandLine(m_view.TxtArgument.getText());
        }
    }// end inner class ClearListener
    
    class ImputBenutzerNameListerner implements KeyListener {

        public void keyTyped(KeyEvent e) {
            m_model.setBenutzername(m_view.TxtBenutzername.getText());
        }

        public void keyPressed(KeyEvent e) {
              m_model.setBenutzername(m_view.TxtBenutzername.getText());
        }

        public void keyReleased(KeyEvent e) {
             m_model.setBenutzername(m_view.TxtBenutzername.getText());
        }
    }// end inner class ClearListener
    
    class ImputPasswortListerner implements KeyListener {

        public void keyTyped(KeyEvent e) {
            m_model.setPasswort(m_view.TxtPasswort.getSelectedText());
        }

        @SuppressWarnings("deprecation")
		public void keyPressed(KeyEvent e) {
             m_model.setPasswort(m_view.TxtPasswort.getText());
        }

        @SuppressWarnings("deprecation")
		public void keyReleased(KeyEvent e) {
             m_model.setPasswort(m_view.TxtPasswort.getText());
        }
    }// end inner class ClearListener
    
   // end inner class ClearListener
}
```


Client.java:


```
package sshsteuerung.Steuerung;

//The client code Client.java:


import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
//import java.util.List;



public class Client {

    ObjectInputStream Sinput;        // to read the socket
    ObjectOutputStream Soutput;    // to write on the socket
    Socket socket;
    XMLDecoder decoder;
    XMLEncoder encoder;

    // Constructor connection receiving a socket number
    Client(int port) {
        // we use "localhost" as host name, the server is on the same machine
        // but you can put the "real" server name or IP address
        try {
            socket = new Socket("localhost",port);
        }
        catch(Exception e) {
            System.out.println("Error connectiong to server:" + e);
            return;
        }
        System.out.println("Connection accepted " +
                socket.getInetAddress() + ":" +
                socket.getPort());

        /* Creating both Data Stream */
        try
        {
            Sinput  = new ObjectInputStream(socket.getInputStream());
            Soutput = new ObjectOutputStream(socket.getOutputStream());
        }
        catch (IOException e) {
            System.out.println("Exception creating new Input/output Streams: " + e);
            e.printStackTrace();
            return;
        }
    }
    
    public XMLDecoder getDecoder() {
    	if (decoder == null) {
    		decoder = new XMLDecoder(Sinput);
    	}
    	return decoder;
    }
    
    public XMLEncoder getEncoder() {
    	if (encoder == null) {
    		encoder = new XMLEncoder(Soutput);
    	}
    	return encoder;
    }
    
    public void send(Object obj) {
       	XMLEncoder encoder = getEncoder();
    	encoder.writeObject(obj);
    	encoder.flush();
    }
    
    public Object read() {
    	XMLDecoder decoder = getDecoder();
    	Object obj = decoder.readObject();
    	return obj;
    
    }
    
    public void closeEncoder() {
    	encoder.close();
    }
    
    public void closeDecoder() {
    	decoder.close();
    }
}
```


Server.java:


```
package sshsteuerung.Steuerung;


import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;





/**
 * This is to help people to write Client server application
 *  I tried to make it as simple as possible... the client connect to the server
 *  the client send a String to the server the server returns it in UPPERCASE thats all
 */
public class Server {
	


    // the socket used by the server
    private ServerSocket serverSocket;
    private SSH2Connection m_sshConnection;
    private Map<String, List<String>> map;
  
    // server constructor
    public Server(int port) throws IOException {
    	
    	map = new HashMap<String, List<String>>();

        /*create socket server and wait for connection requests */
        try
        {
            serverSocket = new ServerSocket(port);
            System.out.println("Server waiting for client on port " + serverSocket.toString());

            while(true)
            {
                Socket socket = serverSocket.accept();  // accept connection
                System.out.println("New client asked for a connection");
                TcpThread t = new TcpThread(socket);    // make a thread of it
                System.out.println("Starting a thread for a new Client");
                t.start();
                try {
					TcpThread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
            }
        }
        catch (IOException e) {
            System.out.println("Exception on new ServerSocket: " + e);
        }
        
    }    

    

//    you must "run" server to have the server run as a console application
    public static void main(String[] arg)throws IOException {
         int port = 11870;
         new Server(port);
        
      }


    
    /** One instance of this thread will run for each client */
	class TcpThread extends Thread {
		// the socket where to listen/talk
		Socket socket;
		ObjectInputStream Sinput;
		ObjectOutputStream Soutput;
		
		TcpThread(Socket socket) {
			this.socket = socket;
		}
		public void run() {
			/* Creating both Data Stream */
			System.out.println("Thread trying to create Object Input/Output Streams");
			try
			{
				// create output first
				Soutput = new ObjectOutputStream(socket.getOutputStream());
				Soutput.flush();
				Sinput  = new ObjectInputStream(socket.getInputStream());
			}
			catch (IOException e) {
				System.out.println("Exception creating new Input/output Streams: " + e);
				return;
			}
			System.out.println("Thread waiting for a String from the Client");
			// read a String (which is an object)
				XMLDecoder decoder = new XMLDecoder(Sinput);
				Object obj = decoder.readObject();
				System.out.println(obj.toString());

			/*finally {
				try {
					Soutput.close();
					Sinput.close();
				}
				catch (Exception e) {					
				}
			}*/
		}
	}
}
```

was soll ich einfügen um als Ausgabe auch ls zu sehen???
MfG.


----------



## eRaaaa (27. Jun 2011)

Mit weniger Code würde sicher jmd helfen können, aber hier wird man überschlagen von Klassen die niemand kennt, inneren Klassen, Listenern etc....
Mach doch mal ein simples Beispiel was ausführbar und von allen nachvollziehbar ist und beschreibe dein Problem mal etwas genauer! Dann kann man dir bestimmt auch weiter helfen.

Was man aber sieht ist, dass du ja keinen String liest sondern eben ein Daten-Objekt:
sshsteuerung.Steuerung.Daten@6f7ce9  <-- nicht "ls" sondern Variable t vermutlich :

Daten t = new Daten();
.....
client.send(t);


Also um deine Frage 





> was soll ich einfügen um als Ausgabe auch ls zu sehen???


zu beantworten anhand folgendem Code

```
if (m_view.getStatusRadioBtn().isSelected()){
            	Client client = new Client(11870);
        		client.send("ls");
        		Object status = client.read();
        		System.out.println(status.toString());
        		client.closeEncoder();
        		client.closeDecoder();
           
        	} else if (m_view.getSSH2RadioBtn().isSelected()) {
            	Daten t = new Daten();
            	t.setBenutzername(m_view.getBenutzerTxt().getText());
            	t.setPasswort(m_view.getPasswordTxf().getText());
            	t.setServeurname(m_view.TxtSName.getText());
            	t.setPrograme(m_view.TxtArgument.getText());
            	t.setCommandLine(m_view.TxtProgramm.getText());
            	Client client = new Client(11870);
            	client.send(t);
            	client.closeEncoder();
        	}
```

würde ich sagen: du musst dne anderen RadioButton (m_view.getStatusRadioBtn()) auswählen


----------



## sanaline (28. Jun 2011)

Ich habe genau andere Button gewählt ("Status"), es muss client.send("ls") ausführen und danach rufe ich das Methode read() von Client aber es scheint nicht zu klappen und ich was nicht warum???


----------

