0

I'm trying to find a reliable way to send control messages that obey a defined protocol in order to tell the server what kind of data he will receive. For example, I want to send a pure text message to invoke a remote method:

#METHOD1#CLOSE#

or I want to send a serialized object to the server:

#OBJECT# .......here comes the serialized object data....#CLOSE#

So basically I just want to send string control messages that are completely independent of the stream content that follows.

By wrapping an input stream into a Scanner object I'm able to extract strings from the input stream, but if this stream is a serialized object then the object can't be restored afterwards. Thanks for any help.

4
  • 1
    Why don't you just use one of the many existing protocols for this purpose? For instance, JSON-RPC? Do you have any specific requirements? Commented May 27, 2013 at 16:14
  • If possible, it should be a pure socket based solution. I just would like to know how this could be done. Commented May 27, 2013 at 16:27
  • 1
    "if possible" is no valid reason. Which is why I asked for your requirements. There is no reason at all to hack your own protocol if an existing one already fits your need. Do not reinvent the wheel! Commented May 27, 2013 at 16:58
  • It's an assignment. Protocols for strings are not a problem, because I can easily append a control message to the actual message string. However, the easierst solution seems to be to subclass ObjectOutputStream. Commented May 27, 2013 at 18:59

1 Answer 1

1

You can use a scheme like Base64 (e.g. use a library from Apache) to encode the Object from bytes into a string and then back.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
new ObjectOutputStream(baos).writeObject(object);
String serializedObject = Base64.encode(baos.toByteArray());

byte[] bytes = Base64.decode(serializedObject);
ByteArrayInputStream baos = new ByteArrayInputStream(bytes);
Object object = new ObjectInputStream(baos).readObject()
Sign up to request clarification or add additional context in comments.

2 Comments

What about Java's BASE64Encoder/Decoder? So, basically I have to encode the object to a string and then append that object string to the control message string, right? To decode the message I read the chars that represent the control message and, if the message says it's an object, I go on adn decode the rest of the string to an object.
Yes, that's right. You can use any Base64 encoder/decoder you like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.