# Mittels BufferedReader Objekte lesen?



## rejo (21. Mai 2006)

Hallo!

Hätt da eine Frage bzgl. Streams. Ich versuche gerade ein Chat zu realisieren.
Ich hätt da einen BufferedReader und ein PrintWriter.
Ich versende gerade durch den PrintWriter Strings 
	
	
	
	





```
pw.println(new String("bla"))
```
 und lese mit dem BufferedReader durch 
	
	
	
	





```
br.readLine();
```
 die Informationen ein. Jedoch würd ich gern Objekte versenden (z.B.: Info über den Empfänger u. Nachricht). 

Aber irgendwie gibt es bei BufferedReader keine Methode um Objekte zu lesen.
Könnt mir da jemand weiterhelfen? Danke schon mal im vorraus! 

Liebe Grüße
rejo


----------



## dieta (21. Mai 2006)

Zum Lesen und Schreiben der Objekte musst du warscheinlich eigene Streams erstellen:
http://java.sun.com/j2se/1.5.0/docs/api/java/io/ObjectOutputStream.html
http://java.sun.com/j2se/1.5.0/docs/api/java/io/ObjectInputStream.html


----------



## byte (21. Mai 2006)

Kleiner Tipp am Rande:

Schreib statt pw.println(new String("bla")) zukünftig einfach nur pw.println("bla"). :roll:


----------



## rejo (21. Mai 2006)

Ich hab schon jetzt eine Woche lang mich geplagt dieses Problem zu lösen! Aber ich bleib immer bei ObjectInputStream und ObjectOutputStream hängen..  :cry: 
Könnt mir jemand bitte weiterhelfen... ich hab schon alles mögliche versucht um BufferedReader und PrintWriter auf ObjectInputStream und ObjectOutputStream zu ändern.. aber während der Laufzeit bleibt es immer hängen wenn 
	
	
	
	





```
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
```
 steht

Bitte könnt mir jemand das etwas detailierter erklären   
Oder vielleicht im Code jene Stellen ändern damit ich Objekte versenden kann anstatt Strings    und etwas kommentieren...
Bitte helft mir :cry:

Liebe Grüße
Rejo  :cry:

EDIT: Danke für den Tipp...


----------



## rejo (21. Mai 2006)

Chat.java

```
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;


public class Chat extends JApplet implements Runnable, ActionListener, ListSelectionListener {

	private static final int PORT = 1080;
	private Socket socket;
	private BufferedReader in;
	private PrintStream out;
	private JTextField inputfield;
	private JTextArea outputarea;
	private Thread thread;
	private String recipient ="";
	private JList userlist;
	private JScrollPane scrollpane;
	private JLabel msghere;

	public void run()
	{
		String line;

		try
		{
			while(true)
			{
				line = in.readLine();
				
				if(line!=null){
					outputarea.append(line + "--> " + recipient +'\n' );
					outputarea.setCaretPosition(outputarea.getDocument().getLength());
				}
					
			}
		} catch (IOException e) { say("Verbindung zum Server abgebrochen"); }
	}
	
	public void init()
	{
		userlist = new JList();
		userlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		userlist.addListSelectionListener(this);
		userlist.setBorder(BorderFactory.createEtchedBorder());
		userlist.setFixedCellWidth(100);
		userlist.setSelectionForeground(Color.BLACK);
		userlist.setSelectionBackground(Color.WHITE);
		
		inputfield = new JTextField();
		inputfield.addActionListener(this);
		outputarea = new JTextArea();
		outputarea.setFont( new Font("Dialog", Font.PLAIN, 12));
		outputarea.setEditable(false);
		inputfield.setBackground(Color.white);
		outputarea.setBackground(Color.white);
		scrollpane = new JScrollPane(outputarea);
		scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		scrollpane.setWheelScrollingEnabled(true);
		msghere = new JLabel("Nachricht: ");
		msghere.setPreferredSize(new Dimension(80,20));
		inputfield.setPreferredSize(new Dimension(500,20));
		JPanel panel = new JPanel();
		panel.setLayout(new FlowLayout());
		panel.add(msghere);
		panel.add(inputfield);
		setLayout(new BorderLayout());
		add("West", userlist);
		add("South",panel);
		add("Center", scrollpane);
		setBackground(Color.lightGray);
		setForeground(Color.black);
	}
	
	public void start()
	{
		try
		{
			socket = new Socket(this.getCodeBase().getHost(), PORT);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e)
		{
			this.showStatus(e.toString());
			say("Verbindung zum Server fehlgeschlagen!");
			System.exit(1);
		}
		say("Verbindung zum Server aufgenommen...");

		if (thread == null)
		{
			thread = new Thread(this);
			thread.start();
		}
	}
	
	public void stop()
	{
		try
		{
			socket.close();
		} catch (IOException e)
		{
			this.showStatus(e.toString());
		}

		if ((thread !=null) && thread.isAlive())
		{
			thread = null;
		}
	}
	
	public void actionPerformed(ActionEvent e)
	{			
		out.println(inputfield.getText());
		inputfield.setText("");
	}
	
	public void say(String msg)
	{
		outputarea.append("*** "+msg+" ***\n");
	}

	public void valueChanged(ListSelectionEvent arg0) {
		 int index = userlist.getSelectedIndex();

		    if (index != -1) {
		      recipient = (String)userlist.getSelectedValue();
		    }
	}
}
```

Server.java

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

public class Server implements Runnable {
	
	private static final int PORT = 1080;
	private ServerSocket listen;
	private Vector connections;
	private Thread connect;
	
	public Server()
	{
		log("Server wird gestartet...");
		try
		{
			listen = new ServerSocket(PORT);
		} catch (IOException e)
		{
			log("Fehler beim Erzeugen der Sockets:"+e);
			System.exit(1);
		}

		connections = new Vector();

		connect = new Thread(this);
		connect.start();
		log("Server ist funktionsbereit");
	}
	
	public void run()
	{
		try
		{
			while(true)
			{
				Socket client=listen.accept();
				Connection c = new Connection(this, client);
				connections.addElement(c);
				log("Neuer Client ist verbunden: " + client.getInetAddress());
			}
		} catch (IOException e) {
			log("Fehler beim Warten auf Verbindungen:"+e);
			System.exit(1);
		}
	}
	
	public void broadcast(String msg)
	{
		Connection you;

		for (int i = 0; i < connections.size(); i++)
		{
			you = (Connection)connections.elementAt(i);
			you.getOut().println(msg);
		}
	}
	
	public void log(String msg) {
		System.out.println("*** " + msg + " ***");
	}
	
	public static void main(String args[]) {
		new Server();
	}
}
```

Connection.java

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

public class Connection extends Thread {

	private Socket client;
	private BufferedReader in;
	private PrintStream out;
	private Server server;
	
	public Connection(Server s, Socket c)
	{
		server=s;
		client=c;
		try
		{
			in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			out = new PrintStream(client.getOutputStream());
		} catch (IOException e)
		{
			try { client.close(); } catch (IOException e2) {} ;
			System.err.println("Fehler beim Erzeugen der Streams: " + e);
			return;
		}

		this.start();
	}
	
	public void run()
	{
		String line;

		try
		{
			while(true)
			{
				line=in.readLine();
				if(line!=null)
					server.broadcast(line);
			}
		} catch (IOException e)
		{
			System.out.println("Fehler:" + e);
		}
	}

	public PrintStream getOut() {
		return out;
	}
	
}
```


----------



## rejo (21. Mai 2006)

Okay hier ist der Code der nicht funktioniert.. also naja "stecken" bleibt...

*Chat.java*

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

import javax.swing.*;
import javax.swing.event.*;


public class Chat extends JApplet implements Runnable, ActionListener, ListSelectionListener {

	private static final int PORT = 1080;
	private Socket socket;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private JTextField inputfield;
	private JTextArea outputarea;
	private Thread thread;
	private String recipient ="";
	private JList userlist;
	private JScrollPane scrollpane;
	private JLabel msghere;

	public void run()
	{
		Message msg = null;
		Object o = null;
		try
		{
			while(true)
			{
				try {
					o = in.readObject();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				
				if(o instanceof Message)
					msg = (Message)o;
				
				
				if(msg!=null){
					outputarea.append(msg.getMessage() + "--> " + recipient +'\n' );
					outputarea.setCaretPosition(outputarea.getDocument().getLength());
				}
					
			}
		} catch (IOException e) { say("Verbindung zum Server abgebrochen"); }
	}
	
	public void init()
	{
		userlist = new JList();
		userlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		userlist.addListSelectionListener(this);
		userlist.setBorder(BorderFactory.createEtchedBorder());
		userlist.setFixedCellWidth(100);
		userlist.setSelectionForeground(Color.BLACK);
		userlist.setSelectionBackground(Color.WHITE);
		
		inputfield = new JTextField();
		inputfield.addActionListener(this);
		outputarea = new JTextArea();
		outputarea.setFont( new Font("Dialog", Font.PLAIN, 12));
		outputarea.setEditable(false);
		inputfield.setBackground(Color.white);
		outputarea.setBackground(Color.white);
		scrollpane = new JScrollPane(outputarea);
		scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		scrollpane.setWheelScrollingEnabled(true);
		msghere = new JLabel("Nachricht: ");
		msghere.setPreferredSize(new Dimension(80,20));
		inputfield.setPreferredSize(new Dimension(500,20));
		JPanel panel = new JPanel();
		panel.setLayout(new FlowLayout());
		panel.add(msghere);
		panel.add(inputfield);
		setLayout(new BorderLayout());
		add("West", userlist);
		add("South",panel);
		add("Center", scrollpane);
		setBackground(Color.lightGray);
		setForeground(Color.black);
	}
	
	public void start()
	{
		try
		{
			socket = new Socket(this.getCodeBase().getHost(), PORT);
			in = new ObjectInputStream(socket.getInputStream());
			out = new ObjectOutputStream(socket.getOutputStream());
		} catch (IOException e)
		{
			this.showStatus(e.toString());
			say("Verbindung zum Server fehlgeschlagen!");
			System.exit(1);
		}
		say("Verbindung zum Server aufgenommen...");

		if (thread == null)
		{
			thread = new Thread(this);
			thread.start();
		}
	}
	
	public void stop()
	{
		try
		{
			socket.close();
		} catch (IOException e)
		{
			this.showStatus(e.toString());
		}

		if ((thread !=null) && thread.isAlive())
		{
			thread = null;
		}
	}
	
	public void actionPerformed(ActionEvent e)
	{	
		Message m = new Message();
		m.setMessage(inputfield.getText());
		m.setRecipient("all");
		try {
			out.writeObject(m);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		inputfield.setText("");
	}
	
	public void say(String msg)
	{
		outputarea.append("*** "+msg+" ***\n");
	}

	public void valueChanged(ListSelectionEvent arg0) {
		 int index = userlist.getSelectedIndex();

		    if (index != -1) {
		      recipient = (String)userlist.getSelectedValue();
		    }
	}
}
```

*Server.java*

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

public class Server implements Runnable {
	
	private static final int PORT = 1080;
	private ServerSocket listen;
	private Vector connections;
	private Thread connect;
	
	public Server()
	{
		log("Server wird gestartet...");
		try
		{
			listen = new ServerSocket(PORT);
		} catch (IOException e)
		{
			log("Fehler beim Erzeugen der Sockets:"+e);
			System.exit(1);
		}

		connections = new Vector();

		connect = new Thread(this);
		connect.start();
		log("Server ist funktionsbereit");
	}
	
	public void run()
	{
		try
		{
			while(true)
			{
				Socket client=listen.accept();
				Connection c = new Connection(this, client);
				connections.addElement(c);
				log("Neuer Client ist verbunden: " + client.getInetAddress());
			}
		} catch (IOException e) {
			log("Fehler beim Warten auf Verbindungen:"+e);
			System.exit(1);
		}
	}
	
	public void broadcast(Message msg)
	{
		Connection you;

		for (int i = 0; i < connections.size(); i++)
		{
			you = (Connection)connections.elementAt(i);
			try {
				you.getOut().writeObject(msg);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void log(String msg) {
		System.out.println("*** " + msg + " ***");
	}
	
	public static void main(String args[]) {
		new Server();
	}
}
```

*Connection.java*

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

public class Connection extends Thread {

	private Socket client;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private Server server;
	
	public Connection(Server s, Socket c)
	{
		server=s;
		client=c;
		try
		{
			in = new ObjectInputStream(client.getInputStream());
			out = new ObjectOutputStream(client.getOutputStream());
		} catch (IOException e)
		{
			try { client.close(); } catch (IOException e2) {} ;
			System.err.println("Fehler beim Erzeugen der Streams: " + e);
			return;
		}

		this.start();
	}
	
	public void run()
	{
		Message msg = null;
		Object o = null;

		try
		{
			while(true)
			{
				try {
					o = in.readObject();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				
				if(o instanceof Message)
					msg = (Message)o;
				
				if(msg!=null)
					server.broadcast(msg);
			}
		} catch (IOException e)
		{
			System.out.println("Fehler:" + e);
		}
	}

	public ObjectOutputStream getOut() {
		return out;
	}
	
}
```

*Message.java*

```
public class Message {

	private String message;
	private String recipient;
	
	public Message() {
		message = null;
		recipient = null;
	}
	
	public Message(String msg, String rec) {
		message = msg;
		recipient = rec;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getRecipient() {
		return recipient;
	}

	public void setRecipient(String recipent) {
		this.recipient = recipent;
	}
	
}
```

Danke


----------

