Java Socket Programming: Dealing with multiple types of messages
I'm develo开发者_运维知识库ping a simple Multicast networked program, and was just curious on the best class structure and OOD patterns that best suit a client/server or client/client network. My dilemma is that I will be sending different kind of messages via datagram, and the receiver just sees a bunch of bytes coming at them. Now, I already implemented a sort of "ID" placeholder as the first byte of all of my byte arrays to distinguish between a message containing "hello world" and one containing the coordinates of a user for instance. The only option seems to be to just have a huge set of case statements in my "receive" method based on what the "ID" is but this seems like bad practice. Just looking for ideas to take advantage of Java's OOD patterns and all-around good coding practice.
On a side note (I think this is somewhat related...) would it be advantageous for me to ues object streams instead? It seemed to me that I would still be checking instancof on everythign coming in. Thanks!
There are several possibilities, but the Strategy Pattern seems to fit the bill best.
In your situation, I would create an interface with at least two methods one to determine if the class can handle the message (which will check your ID bits) and another to actually process the message. Then you create a separate message processing class for each type of message.
Your incoming message handler would then have a set or list of these message processing objects (typically each of a different class, but all of whom implement the interface). When a message is received, the message handler would iterate through the message processing objects until one can handle the message is found, giving an error if no message processor will handle the message.
There are a few options here, depending on circumstances.
You can certainly send serialized objects, one for each message type. Serialized Java objects typically only work between Java apps, but you can aslo try protocol buffers for interoperable Objects (http://code.google.com/p/protobuf/)
You can send documents in an interoperable format like JSON or XML
You can make up your own format, and parse the text as you like
me, i would probably go with Protocol Buffers
精彩评论