Using Serialization with non-blocking sockets

Posted by on noiembrie 11, 2007
Fără categorie

The most common way to make a server in Java is to create a thread pool and associate each request with a thread. Java5 offers a special class called Executor that can help you with the task. However, if you ever needed to make a server which can handle thousands of connections, you know this solution doesn’t scale very well. Most processors can’t handle more than a few hundreds of threads.
The solution is to use non-blocking sockets, a feature introduced in java 1.4 (the java.nio package). However, this has an important drawback: you can’t use the getInputStream(), getOutputStream() functions from the Socket class to serialize objects. The reason is simple: with non-blocking sockets, there is no way the system can guarantee that the whole object has been sent/received.
You can however „trick” the virtual machine by using explicit Streams. You have a simple example below. We try to send an object with the Message type.

  • The sending end

    Message outgoingMessage;
    SocketChannel socketChannel;
    //we open the channel and connect
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    objectOutputStream.writeObject(outgoingMessage);
    objectOutputStream.flush();
    socketChannel.write(ByteBuffer.wrap(byteArrayOutputStream.toByteArray()));
  • The receiving end

    SocketChannel socketChannel;
    ByteBuffer data;
    //we open the channel and connect
    socketChannel.read(data);
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data.array());
    ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
    Message message = (Message)objectInputStream.readObject();

The code works if you receive the whole object or more than one object (the readObject() function reads exactly one object). However, I had some issues with reconstructing the object if it arrived in multiple pieces. Any suggestions on that part would be useful.
Here are some resources that I found useful: a discussion at forum.java.sun.com and another discution about the subject.

2 Comments to Using Serialization with non-blocking sockets

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.