开发者

Sending several datatypes to remote server

I am programming a client and server in Java where the client sends a request to create a Certificate. This request contains a lot of different datatypes including byte [], the way that I am doing it now is by using ObjectStreams like :

objectStream.writeObject( new String("value of field1"));
objectStream.flush();
objectStream.writeObject( new String("value of field"));
objectStream.flush();
objectStream.writeObject( publicKey);
objectStream.flush();
...

Now I know that this is p开发者_JS百科retty bad design but I'm not quite sure how to improve it.

Would XML be a good Idea??

thanks,


You have several options:

  • make your object Serilazible by implementing the interface and make sure that all the fields are serializable as well (byte[] is). Then you can just call objectStream.writeObject(myObj);
  • XML is not a bad idea. If the other side is always Java you can use the XMLEncoder and XMLDecoder to convert to/from the XML and send it over the wire. A heavier alternative will be to use JAXB - read a bit about it before jumping in as its usage is more complicated (but then you can have the other side in other language as well)


Now I know that this is pretty bad design

Why do you think so? Java serialization is easy to use and works. Don't complicate things needlessly.

Do you know that you'll have to accomodate non-Java participants, or evolve the protocol without being able to update existing clients? Those would be reasons to worry about the protocol. Otherwise, do the simplest thing that works. Put all the fields in a class, make that Serializable, and it's even simpler than what you're doing now. Make sure you keep all logic related to that in one place, and if and when you need a more portable protocol, it won't be too hard to serialize to XML or JSON instead of an ObjectOutputStream.


Have you considered using RMI if the whole application is built in Java and doesn't have to include other platforms?

You still have to deal with serialization, however you could implement your application more natively and don't have to bother with things like marshalling/unmarshalling or low-level serialization.


Using Java serialization ties both server and client to Java and also makes upgrading either problematic (yes there are plenty of ways around it, but it's a frequent source of problems). XML is pretty verbose, while is ok for small amounts of data, but doesn't scale well.

I'd suggest using something like JSON, or FUDGE which let you send name value pairs in a pretty concise encoding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜