ChatMan (tm) a chat management program that I’m working on now has to handle multiple clients and send all the clients the most recent messages that they have not yet seen.

Reading and writing a single line from Client to Server was relatively simple due to the .readLine() method that exists on the BufferedReader class of Java, but reading the entire message history is a little bit more complex.

At the moment I add all messages the Client writes to an ArrayList which I write to a BufferedReader and read line by line back to the Client. Every time a new word is added, this gets added to the messageHistory ArrayList and sent back to the Client by being written to an OutputStream.

private BufferedReader writeMessagesToBuffer() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] bytes = outputStream.toByteArray();
return createBufferedReader(bytes);

I then write the contents of the buffered reader back to the output stream that is sent to the Client.

public void writeBackToClient(BufferedReader bufferedReader, ConnectionSocket socket) throws IOException {
String words;
StreamWriter out = socket.getOutputStream();
while ((words = bufferedReader.readLine()) != null) {
out.writeBytes(words + '\n');

This is a relatively simple implementation of sending a group of messages back and forth between a client and server. The next stage is to send a group of 3 messages across and finally determine which messages to send based on the times the messages were sent. Breaking down these stories has really helped.

So the next part I will focus on is to create an object that represents these 3 messages I want to send across. I am sure that there is some form of counter that I could use along with a loop. But I got a hint in my IPM to use Java’s Serialisable class.

The Serialisable class in Java can break down certain objects into their byte components and then pass them around, even to another JVM to be deserialised and recomposed. It is just another way to persist data, I suppose another way would be to write the information you are trying to hold on to to a database, but for simple information Serialisable is a good class to use.

In order to be serialisable the object has to be written to a FileInputStream initially, so that that an ObjectOutputSream can be created out of it.

Then using the writeObject(Object to serialise) method you can write the object to the ObjectOutputStream. Deserialising an object is done using by using an ObjectInputStream that you read from the same file using .readObject().

Sounds relatively simple, I will try and implement it tomorrow with a MessageList object that holds on to 3 messages from the Client and uses Serialisable to send them to the Server to be deserialised and then sent back to the Client again.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.