# Nullpointer Exception - Multithreading



## Guest (8. Jul 2008)

Guten Morgen, bei mir fliegt beim starten des Clients eine Nullpointer exception.
Server.java line 33
Ich kann nur nicht nachvollziehen warum


```
import java.net.*;
import java.io.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Server extends Thread {

    Boolean isStarted = false;
    ServerSocket server;
    Socket client;
    DataOutputStream out;
    DataInputStream in;
    List<ClientData> list;
    
    
    
    @Override
    public synchronized void run() {
        try {
            server = new ServerSocket(4000);
        } catch (IOException ex) {
            System.out.println("Probleme mit Socket");
        }
        while (isStarted) {
            try {
                client = server.accept();
                in = new DataInputStream(client.getInputStream());
                out = new DataOutputStream(client.getOutputStream());
                ClientData cl = new ClientData(client, out);
                String chatNachricht = in.readUTF();
                System.out.println(chatNachricht);
                list.add(cl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try { 
            server.close();
            client.close();
        } catch (IOException ex) {
            System.out.println("put");
        }

    }

    
    public void writeToAll(String x) {
         for (ClientData d : list) {
            try {
                d.getOutputStream().writeUTF(x);
                d.getOutputStream().flush();
            } catch (IOException ex) {
                System.out.println("Fehler beim erzeugen der Nachricht");
            }
         }
    }
    
    public List getClients() {
        return list;
    }
    
      
    public void removeClient(Socket client) {
        list.remove(client);
    }
    
    public void setOffline() {
        isStarted = false;
    }

    public void setOnline() {
        isStarted = true;
    }
}
```


```
import java.net.*;
import java.io.*;


public class Client {

	Client() throws IOException {
		Socket server = new Socket("localhost", 4000);
		DataOutputStream out = new DataOutputStream(server.getOutputStream());
		DataInputStream in = new DataInputStream(server.getInputStream());
		out.writeUTF("login331");
		//out.writeUTF("passwort");
		out.flush();
		System.out.println(in.readUTF());
		//System.out.println(input.read());
		server.close();
		out.close();
		
		
	}
	
	public static void main(String[] args) {
		try {
			Client client = new Client();
		} catch (IOException e) {
			System.err.println("Fehler: " + e);
		}
	}
}
```


----------



## HoaX (8. Jul 2008)

weil das objekt null ist? in deinem geposteten code ist das allerdings zeile 35 imo


----------



## Guest (8. Jul 2008)

ja aber wie kann das sein... ich erstelle doch zuvor ein objekt


----------



## tfa (8. Jul 2008)

Wo erstellst du das list-Objekt?


----------



## tuxedo (8. Jul 2008)

>> List<ClientData> list; 

Da fehlt eben ein "new" ... ;-)


----------



## Guest (8. Jul 2008)

ok das war nen wirklich dummer fehler.
hab das korrigiert. jetzt habe ich das phänomen, dass die ersten zwei nachrichten an dne client zurückgeschickt werden es aber bei jeder weiteren eine fehlermeldung gibt.

java.net.SocketException: Software caused connection abort: socket write error
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
        at java.io.DataOutputStream.write(DataOutputStream.java:90)
        at java.io.DataOutputStream.writeUTF(DataOutputStream.java:384)
        at java.io.DataOutputStream.writeUTF(DataOutputStream.java:306)
        at Server.writeToAll(Server.java:59)
        at Server.run(Server.java:42)



```
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Server extends Thread {

    Boolean isStarted = false;
    ServerSocket server;
    Socket client;
    DataOutputStream out;
    DataInputStream in;
    List<ClientData> list = new ArrayList();
    ClientData cl = null;
    
    
    
    @Override
    public synchronized void run() {
        try {
            server = new ServerSocket(4000);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        while (isStarted) {
            try {
                client = server.accept();
                in = new DataInputStream(client.getInputStream());
                out = new DataOutputStream(client.getOutputStream());
                if (client != null && out != null) {
                    cl = new ClientData(client, out);
                }
                String chatNachricht = in.readUTF();
                System.out.println(chatNachricht);
                if(cl != null) {
                    list.add(cl);
                }
                writeToAll(chatNachricht);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try { 
            server.close();
            client.close();
        } catch (IOException ex) {
            System.out.println("put");
        }
    }

    
    public void writeToAll(String x) {
         for (ClientData d : list) {
            try {
                d.getOutputStream().writeUTF(x);
                d.getOutputStream().flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
         }
    }
    
    public void closeAll(String x) {
         for (ClientData d : list) {
           
         }
    }
    
    public List getClients() {
        return list;
    }
    
      
    public void removeClient(Socket client) {
        list.remove(client);
    }
    
    public void setOffline() {
        isStarted = false;
    }

    public void setOnline() {
        isStarted = true;
    }
}
```


----------



## SlaterB (8. Jul 2008)

der Client schließt seine Verbindung wenige ms nach dem Zustandekommen,
dann kann der Server nicht beim nächsten Client noch was schicken


----------



## Guest (8. Jul 2008)

ich erhalte leider noch dne selben fehler:


```
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Server extends Thread {

    Boolean isStarted = false;
    ServerSocket server;
    Socket client;
    DataOutputStream out;
    DataInputStream in;
    List<ClientData> list = new ArrayList();
    ClientData cl = null;
    
    
    
    @Override
    public synchronized void run() {
        try {
            server = new ServerSocket(4000);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        while (isStarted) {
            try {
                client = server.accept();
                in = new DataInputStream(client.getInputStream());
                out = new DataOutputStream(client.getOutputStream());
                if (client != null && out != null) {
                    cl = new ClientData(client, out);
                }
                String chatNachricht = in.readUTF();
                System.out.println(chatNachricht);
                if(cl != null) {
                    list.add(cl);
                }
                writeToAll(chatNachricht);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //try { 
            //server.close();
            //client.close();
        //} catch (IOException ex) {
        //    System.out.println("put");
        //}
    }

    
    public void writeToAll(String x) {
         for (ClientData d : list) {
            try {
                d.getOutputStream().writeUTF(x);
                d.getOutputStream().flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
         }
    }
    
    public void closeAll(String x) {
         for (ClientData d : list) {
           
         }
    }
    
    public List getClients() {
        return list;
    }
    
      
    public void removeClient(Socket client) {
        list.remove(client);
    }
    
    public void setOffline() {
        isStarted = false;
    }

    public void setOnline() {
        isStarted = true;
    }
}
```


----------



## SlaterB (8. Jul 2008)

weil du nichts geändert hast, 
der Code, den du auskommentierst hast, wurde doch gar nicht ausgeführt (mit System.out.println() leicht zu testen)

ich rede von der Klasse Client, Zeile 16


----------



## Gast (8. Jul 2008)

ok - ist es denn nicht ein speicherproblem, wenn ich die verbindungen nicht close?

import java.net.*;
import java.io.*;


public class Client {

    String nachricht = "Standard";
    Socket server;
    DataOutputStream out;
    DataInputStream in;

	Client(String chatNachricht) throws IOException {
                try {
		server = new Socket("172.28.130.79", 4000);
                out = new DataOutputStream(server.getOutputStream());
		in = new DataInputStream(server.getInputStream());
		out.writeUTF(chatNachricht);
		out.flush();
		this.nachricht = in.readUTF();
		//System.out.println(input.read());
		} catch (Throwable e) {
                    this.nachricht="Fehler - Server konnte nicht erreicht werden.";
                } finally {
                //server.close();
		//out.close();
                //in.close();
                }
	}

        public String getNachricht() {
            return nachricht;
        }
}


----------



## SlaterB (8. Jul 2008)

tja, es ist auch ein Speicherproblem, wenn du das Programm überhaupt startest,
wenn nicht oder gar der Computer aus bleibt, dann ist der Speicher schön leer 

das ist ja kein Argument, 
wenn du auf dem Server die Socket-Verbindung speicherst um später noch was reinzuschreiben,
dann muss der Client die Verbindung offen halten und außerdem noch die ganze Zeit zuhören,
sonst macht das doch keinen Sinn?!?

wozu sich für einen Newsletter anmelden, wenn man sofort seinen Email-Account wieder löscht?


----------



## Gast (8. Jul 2008)

also ist es so richtig?
Kannst du auch nochmal einen Blick auf meine Liste werfen?
mir scheint es so, als wenn sich ein client mehrmals in die liste schreibt. kann ich irgendwie überprüfen, ob der client bereits in der liste ist?


----------



## Guest (8. Jul 2008)

```
while (isStarted) {
            try {
                client = server.accept();
                in = new DataInputStream(client.getInputStream());
                out = new DataOutputStream(client.getOutputStream());
                if (client != null && out != null) {
                    cl = new ClientData(client, out);
                }
                String chatNachricht = in.readUTF();
                System.out.println(chatNachricht);
                if (cl != null) {
                    if (list.contains(cl)) {
                        System.out.println("Objekt existiert bereits in der Liste");
                    } else {
                        list.add(cl);
                    }
                }
                writeToAll(chatNachricht);
            } catch (Exception e) {
                e.printStackTrace();
            }
```

das ist mein ansatz - allerdings werden trotz alledem wird dasselbe objekte mehrmals in die liste hineingesteckt


----------



## SlaterB (8. Jul 2008)

was läßt dich das denn vermuten?, 
logge dich mit was so passiert, die Anzahl der Elemente darin, IP + Port des jeweiligen Sockets usw.

zwei einzelne ClientData-Objekte sind verschieden, sofern du die equals-Operation nicht passend überschreibst,
ich sehe aber auch keine Möglichkeit, dass da irgendwas doppelt reinkommt

wenn sich der Client mehrmals zum Server connected, dann sind das natürlich mehrere verschiedene Verbindungen,
nach welcher Logik sollten die gleich sein?


----------



## Guest (8. Jul 2008)

```
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server extends Thread {

    Boolean isStarted = false;
    ServerSocket server;
    Socket client;
    DataOutputStream out;
    DataInputStream in;
    HashSet<ClientData> list = new HashSet();
    ClientData cl = null;

    @Override
    public synchronized void run() {
        try {
            server = new ServerSocket(4000);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        while (isStarted) {
            try {
                client = server.accept();
                in = new DataInputStream(client.getInputStream());
                out = new DataOutputStream(client.getOutputStream());
                if ((client != null) && (out != null)) {
                    cl = new ClientData(client, out);
                }
                String chatNachricht = in.readUTF();
                System.out.println(chatNachricht);
                if (cl != null) {
                    if (list.contains(cl)) {
                        System.out.println("Objekt existiert bereits in der Liste");
                    } else {
                        System.out.println("Eintrag in Liste erzeugt");
                        list.add(cl);
                    }
                }
                writeToAll(chatNachricht);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            server.close();
            client.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void writeToAll(String x) {
        for (ClientData d : list) {
            try {
                System.out.println(d.getSocket());
                d.getOutputStream().writeUTF(x);
                d.getOutputStream().flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void closeAll(String x) {
        for (ClientData d : list) {
        }
    }

    public HashSet getClients() {
        return list;
    }

    public void removeClient(Socket client) {
        list.remove(client);
    }

    public void setOffline() {
        isStarted = false;
    }

    public void setOnline() {
        isStarted = true;
    }
}
```

meine aktuelle Fehlermeldung
init:
deps-jar:
compile:
run:
fff
Eintrag in Liste erzeugt
Socket[addr=/127.0.0.1,port=1920,localport=4000]
dddd
Eintrag in Liste erzeugt
Socket[addr=/127.0.0.1,port=1920,localport=4000]
Socket[addr=/127.0.0.1,port=1921,localport=4000]
gggg
Eintrag in Liste erzeugt
Socket[addr=/127.0.0.1,port=1922,localport=4000]
Socket[addr=/127.0.0.1,port=1920,localport=4000]
Socket[addr=/127.0.0.1,port=1921,localport=4000]
java.net.SocketException: Software caused connection abort: socket write error
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
        at java.io.DataOutputStream.write(DataOutputStream.java:90)
        at java.io.DataOutputStream.writeUTF(DataOutputStream.java:384)
        at java.io.DataOutputStream.writeUTF(DataOutputStream.java:306)
        at Server.writeToAll(Server.java:63)
        at Server.run(Server.java:46)
aaaaa
Eintrag in Liste erzeugt
Socket[addr=/127.0.0.1,port=1922,localport=4000]
Socket[addr=/127.0.0.1,port=1923,localport=4000]
Socket[addr=/127.0.0.1,port=1920,localport=4000]
Socket[addr=/127.0.0.1,port=1921,localport=4000]


Wie kann es denn sein, dass hier mehrere sockets in der liste stehen?


```
import java.net.*;
import java.io.*;


public class Client {

    String nachricht = "Standard";
    Socket server;
    DataOutputStream out;
    DataInputStream in;
    Boolean eingeloogt = false;

    Client(String chatNachricht) throws IOException {
        try {
            if (!eingeloogt) {
                server = new Socket("localhost", 4000);
                eingeloogt = true;
            }
            out = new DataOutputStream(server.getOutputStream());
            in = new DataInputStream(server.getInputStream());
            out.writeUTF(chatNachricht);
            out.flush();
            this.nachricht = in.readUTF();
        //System.out.println(input.read());
        } catch (Throwable e) {
            this.nachricht = e.getMessage().toString();
        }
    }

    public String getNachricht() {
        return nachricht;
    }

    public void beendeClient() {
        try {
            server.close();
            out.close();
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}
```


----------



## SlaterB (8. Jul 2008)

z.B. weil irgendwo in deinem Programm mehrmals new Client() ausgeführt wird,
du musst komplettere Programm posten von der main an,

und falls du mehrere Einzelprogramme startest, musst du genau beschreiben welche wann


----------



## Guest (8. Jul 2008)

ok dann fasse ich nochmal zusammen:

// Client Anwendung


Client.java



```
import java.net.*;
import java.io.*;


public class Client {

    String nachricht = "Standard";
    Socket server;
    DataOutputStream out;
    DataInputStream in;
    Boolean eingeloogt = false;

    Client(String chatNachricht) throws IOException {
        try {
            if (!eingeloogt) {
                server = new Socket("localhost", 4000);
                eingeloogt = true;
            }
            out = new DataOutputStream(server.getOutputStream());
            in = new DataInputStream(server.getInputStream());
            out.writeUTF(chatNachricht);
            out.flush();
            this.nachricht = in.readUTF();
        //System.out.println(input.read());
        } catch (Throwable e) {
            this.nachricht = e.getMessage().toString();
        }
    }

    public String getNachricht() {
        return nachricht;
    }

    public void beendeClient() {
        try {
            server.close();
            out.close();
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}
```

ClientStart.java

```
import java.awt.event.ActionListener;

/*
 * Client.java
 *
 * Created on 7. Juli 2008, 13:55
 */
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;



/**
 *
 * @author  bmr
 */
public class ClientStart extends javax.swing.JFrame implements ActionListener {

    String username;
    
    
    /** Creates new form Client */
    public ClientStart() {
        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() {

        jLabel1 = new javax.swing.JLabel();
        chatNachricht = new javax.swing.JTextField();
        abschicken = new javax.swing.JToggleButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        chatArea = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        nickname = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("Bundle"); // NOI18N
        jLabel1.setText(bundle.getString("ClientStart.jLabel1.text_1")); // NOI18N

        chatNachricht.setText(bundle.getString("ClientStart.chatNachricht.text_1")); // NOI18N

        abschicken.setText(bundle.getString("ClientStart.abschicken.text")); // NOI18N
        abschicken.addActionListener(this);

        chatArea.setColumns(20);
        chatArea.setRows(5);
        jScrollPane1.setViewportView(chatArea);

        jLabel3.setText(bundle.getString("ClientStart.jLabel3.text")); // NOI18N

        nickname.setText(bundle.getString("ClientStart.nickname.text")); // NOI18N

        jLabel2.setText(bundle.getString("ClientStart.jLabel2.text")); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(220, 220, 220)
                        .add(abschicken))
                    .add(layout.createSequentialGroup()
                        .add(249, 249, 249)
                        .add(jLabel3))
                    .add(layout.createSequentialGroup()
                        .add(59, 59, 59)
                        .add(jLabel1)
                        .add(18, 18, 18)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 332, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(chatNachricht, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 330, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 33, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel2)
                    .add(nickname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(jLabel3)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 347, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 71, Short.MAX_VALUE)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(chatNachricht, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel1))
                        .add(18, 18, 18)
                        .add(abschicken)
                        .add(36, 36, 36))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(jLabel2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(nickname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(35, 35, 35))))
        );

        pack();
    }

    // Code for dispatching events from components to event handlers.

    public void actionPerformed(java.awt.event.ActionEvent evt) {
        if (evt.getSource() == abschicken) {
            ClientStart.this.abschickenActionPerformed(evt);
        }
    }// </editor-fold>                        

private void abschickenActionPerformed(java.awt.event.ActionEvent evt) {                                           
        try {
            Client cl = new Client(chatNachricht.getText());
            this.username = nickname.getText();
            chatArea.append(username + ": " + cl.getNachricht() + "\n");
            getContentPane().validate();
            getContentPane().repaint();
            
        } catch (IOException ex) {
            Logger.getLogger(ClientStart.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Client Fehler");
        }
        
}                                          

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientStart().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JToggleButton abschicken;
    private javax.swing.JTextArea chatArea;
    private javax.swing.JTextField chatNachricht;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField nickname;
    // End of variables declaration                   

}
```

// Server Anwendung
ClientData.java

```
import java.io.DataOutputStream;
import java.net.Socket;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


/**
 *
 * @author bmr
 */
public class ClientData {

private Socket socket; 
private DataOutputStream out; 


    public ClientData(Socket socket, DataOutputStream out) {
        this.socket = socket;
        this.out = out;
    }

    
    public DataOutputStream getOutputStream() {
        return out;
    }
    
    public Socket getSocket() {
        return socket;
    }
}
```

Server.java

```
import java.net.*;
import java.io.*;
import java.util.HashSet;
import java.util.Vector;


public class Server extends Thread {

    Boolean isStarted = false;
    ServerSocket server;
    Socket client;
    DataOutputStream out;
    DataInputStream in;
    Vector<ClientData> list = new Vector<ClientData>();

    ClientData cl = null;

    @Override
    public synchronized void run() {
        try {
            server = new ServerSocket(4000);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        while (isStarted) {
            try {
                client = server.accept();
                in = new DataInputStream(client.getInputStream());
                out = new DataOutputStream(client.getOutputStream());
                if ((client != null) && (out != null)) {
                    cl = new ClientData(client, out);
                }
                String chatNachricht = in.readUTF();
                System.out.println(chatNachricht);
                if (cl != null) {
                    if (list.contains(cl)) {
                        System.out.println("Objekt existiert bereits in der Liste");
                    } else {
                        System.out.println("Eintrag in Liste erzeugt");
                        list.add(cl);
                    }
                }
                writeToAll(chatNachricht);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            server.close();
            client.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void writeToAll(String x) {
        for (ClientData d : list) {
            try {
                System.out.println(d.getSocket());
                d.getOutputStream().writeUTF(x);
                d.getOutputStream().flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void closeAll(String x) {
        for (ClientData d : list) {
        }
    }

    public Vector getClients() {
        return list;
    }

    public void removeClient(Socket client) {
        list.remove(client);
    }

    public void setOffline() {
        isStarted = false;
    }

    public void setOnline() {
        isStarted = true;
    }
}
```

ServerStart.java

```
import java.awt.event.ActionListener;

/*
 * Server.java
 *
 * Created on 7. Juli 2008, 10:49
 */
/**
 *
 * @author  bmr
 */
public class ServerStart extends javax.swing.JFrame implements ActionListener {

    Server s = null;

    /** Creates new form Server */
    public ServerStart() {
        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() {

        mainPanel = new javax.swing.JPanel();
        serverStarten = new javax.swing.JButton();
        serverBeenden = new javax.swing.JButton();
        statusLabel = new javax.swing.JLabel();
        serverStatus = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("Bundle"); // NOI18N
        setTitle(bundle.getString("ServerStart.title")); // NOI18N
        setName("ServerFrame"); // NOI18N
        setResizable(false);

        serverStarten.setText(bundle.getString("ServerStart.serverStarten.text")); // NOI18N
        serverStarten.addActionListener(this);

        serverBeenden.setText(bundle.getString("ServerStart.serverBeenden.text")); // NOI18N
        serverBeenden.addActionListener(this);

        statusLabel.setText(bundle.getString("ServerStart.statusLabel.text")); // NOI18N

        serverStatus.setText(bundle.getString("ServerStart.serverStatus.text")); // NOI18N

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .add(54, 54, 54)
                .add(statusLabel)
                .add(57, 57, 57)
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                        .add(serverBeenden, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(serverStarten, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .add(serverStatus, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 220, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .add(30, 30, 30)
                .add(serverStarten)
                .add(18, 18, 18)
                .add(serverBeenden)
                .add(54, 54, 54)
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusLabel)
                    .add(serverStatus))
                .addContainerGap(127, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(mainPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(mainPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }

    // Code for dispatching events from components to event handlers.

    public void actionPerformed(java.awt.event.ActionEvent evt) {
        if (evt.getSource() == serverStarten) {
            ServerStart.this.serverStartenActionPerformed(evt);
        }
        else if (evt.getSource() == serverBeenden) {
            ServerStart.this.serverBeendenActionPerformed(evt);
        }
    }// </editor-fold>                        

private void serverStartenActionPerformed(java.awt.event.ActionEvent evt) {                                              
    try {
    if (s == null) {
        s = new Server();
        s.start();
        s.setOnline();
        serverStatus.setText("Server gestartet");
    } else if (s != null) {
        if (s.isStarted) {
            serverStatus.setText("Server ist bereits gestartet");
        } else if (!(s.isStarted)) {
           //s = new Server();
           // s.start();
            s.setOnline();
            serverStatus.setText("Server gestartet");
        }
    }
    mainPanel.validate();
    mainPanel.repaint();
    } catch (Exception e) {
        e.printStackTrace();
    }
}                                             

private void serverBeendenActionPerformed(java.awt.event.ActionEvent evt) {                                              
    s.setOffline();
    serverStatus.setText("Server beendet");
    mainPanel.validate();
    mainPanel.repaint();
}                                             

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ServerStart().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel mainPanel;
    private javax.swing.JButton serverBeenden;
    private javax.swing.JButton serverStarten;
    private javax.swing.JLabel serverStatus;
    private javax.swing.JLabel statusLabel;
    // End of variables declaration                   

}
```


----------



## SlaterB (8. Jul 2008)

> private void abschickenActionPerformed(java.awt.event.ActionEvent evt) {                                            
>        try { 
>            Client cl = new Client(chatNachricht.getText()); 

hier wird für jede Nachricht ein neuer Client erstellt,
reicht nicht einer, in welchem du mehrmals etwas reinschreibst?

nachdem die Clients erzeugt sind interessiert du dich auch nicht weiter für sie,
der Client-Konstruktor wird nach der ersten Nachricht beendet,
danach schwebt derSocket herum,
niemand sammelt ihn auf um ihn später mal zu beenden, niemand horcht, ob später weitere Nachrichten kommen,

immerhin könnte das Fehlen von Referenzen auf den Socket dazu führen, dass dieser automatisch geschlossen wird?,
das würde die Exception erklären, kann ich aber nicht genau sagen


----------



## Guest (8. Jul 2008)

was hälst du von dieser variante



```
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Client {

    String nachricht = "Standard";
    Socket server;
    DataOutputStream out;
    DataInputStream in;
    Boolean eingeloogt = false;

    Client() throws IOException {
        try {
            server = new Socket("localhost", 4000);
            eingeloogt = true;
            out = new DataOutputStream(server.getOutputStream());
            in = new DataInputStream(server.getInputStream());
        //System.out.println(input.read());
        } catch (Throwable e) {
            this.nachricht = e.getMessage().toString();
        }
    }

    public String getNachricht() {
        return nachricht;
    }

    public void verschickeNachricht(String chatNachricht) {
        try {
            out.writeUTF(chatNachricht);
            out.flush();
            this.nachricht = in.readUTF();
        } catch (Exception ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            this.nachricht = ex.getMessage().toString();
            ex.printStackTrace();
        }
    }

    public void beendeClient() {
        try {
            server.close();
            out.close();
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}
```


----------



## SlaterB (8. Jul 2008)

schön


----------



## Gast (8. Jul 2008)

beim abschicken einer nachricht erhalte ich eine nullpointer fehlermeldung:

08.07.2008 13:03:48 Client verschickeNachricht
SCHWERWIEGEND: null
java.lang.NullPointerException
        at Client.verschickeNachricht(Client.java:33)
        at ClientStart.abschickenActionPerformed(ClientStart.java:132)
        at ClientStart.actionPerformed(ClientStart.java:122)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
        at javax.swing.JToggleButton$ToggleButtonModel.setPressed(JToggleButton.java:269)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:5517)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
        at java.awt.Component.processEvent(Component.java:5282)
        at java.awt.Container.processEvent(Container.java:1966)
        at java.awt.Component.dispatchEventImpl(Component.java:3984)
        at java.awt.Container.dispatchEventImpl(Container.java:2024)
        at java.awt.Component.dispatchEvent(Component.java:3819)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
        at java.awt.Container.dispatchEventImpl(Container.java:2010)
        at java.awt.Window.dispatchEventImpl(Window.java:1791)
        at java.awt.Component.dispatchEvent(Component.java:3819)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at Client.verschickeNachricht(Client.java:38)
        at ClientStart.abschickenActionPerformed(ClientStart.java:132)
        at ClientStart.actionPerformed(ClientStart.java:122)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
        at javax.swing.JToggleButton$ToggleButtonModel.setPressed(JToggleButton.java:269)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:5517)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
        at java.awt.Component.processEvent(Component.java:5282)
        at java.awt.Container.processEvent(Container.java:1966)
        at java.awt.Component.dispatchEventImpl(Component.java:3984)
        at java.awt.Container.dispatchEventImpl(Container.java:2024)
        at java.awt.Component.dispatchEvent(Component.java:3819)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
        at java.awt.Container.dispatchEventImpl(Container.java:2010)
        at java.awt.Window.dispatchEventImpl(Window.java:1791)
        at java.awt.Component.dispatchEvent(Component.java:3819)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
BUILD SUCCESSFUL (total time: 6 secon



das darf doch wohl nicht war sein :-(


achso... danke das du hier schon den ganzen tag über meinen code schaust!


----------



## Mark110 (8. Jul 2008)

so sieht meine methode abschicken aus

```
private void abschickenActionPerformed(java.awt.event.ActionEvent evt) {                                           

    if (!isInstantiated) {
        cl = new Client();
        isInstantiated = true;
    }
    cl.verschickeNachricht(chatNachricht.getText());
    this.username = nickname.getText();
    chatArea.append(username + ": " + cl.getNachricht() + "\n");
    getContentPane().validate();
    getContentPane().repaint();



}
```


----------



## SlaterB (8. Jul 2008)

weil in Zeile 33 irgendwas null ist,
ich kann das im Moment nicht erahnen, z.B. dürfte out nicht null sein,
falls nicht im Konstruktor eine Exception auftrat, die du mangels Logging gar nicht sehen würdest,

da das aber langsam zu einem Pinp Pong um jeden einzelnen Programmierschritt wird,
mache ich nicht mehr mit,
viel Erfolg weiterhin


----------



## tuxedo (8. Jul 2008)

In Zeile 33 deiner Client.java ist irgendwas null. Da du den Code schon wieder geändert hast: Kein Plan was in Zeile 33 steht. Aber es schadet nix wenn mal lernt Exceptions zu lesen.

- Alex


----------



## FArt (8. Jul 2008)

SlaterB hat gesagt.:
			
		

> schön



Nö, müsste ich ein Codereview dafür machen, gäbe es noch viel Arbeit. Das sieht nach unsauberem Umgang mit Betriebssystem-Ressourcen (Streams, Sockets) aus. Und wieso "synchronized run()" ???


----------



## SlaterB (8. Jul 2008)

'schön' hieß ja auch 'nicht zu beurteilen, allgemeine Mecker eh ausgeklammert'


----------

