Implement protocol for java client (Android) and C# server
I implemented on Android a small application that sends through a socket connection strings to a server ( C# ).
For now, I only encode the strings I send ( security issues ), but now I need to implement a protocol to have other features on my App like a "keep alive" message, among others.
The procotol was already defined by us, it has a header ( a sequence of bytes ) and the data ( the strings that I sent before ), but because I am not familiar with this I don't know how to start implementing on Java ( client ) the protocol.
Could you point some examples of simple protocols implementation? I need to read bytes, so I can decide what type of action the client is asking from the server, and the other way around too.
My first try would be to create one class for each Message type, and fill the bytes the way i need, in the end each message would be a byte array. But I don't want to start digging on开发者_如何学C this before I am sure that that's the right path to go.
Thank you for your time.
EDIT
Ended using Protocol Buffers for implementing this:
http://code.google.com/p/protobuf-net/ - for the c# server side
http://code.google.com/p/protobuf-javame/ - for the Android side
I faced the same problem some time ago. If you have enough bandwidth then I suggest you go XML and XML streams, these two technologies fit very well in all platforms and all languages. However, if you are short of bandwidth then yes you can go binary. Here is the design I usually use:
class AbstractMessage{
byte[] data;
void GenerateHeader(){
// this method generates the message header
}
// Use this method to translate your
// business domain message into a byte array that will go through the network
void abstract byte[] ToByteArray(AbstractMessage);
// Translate received data from network to a business domain message
void abstract AbstractMessage ParseMessage(byte[] receivedData)
}
// And then you can have your messages
class MyMessage extends AbstractMessage{
// In this subclass, you can define how a
// MyMessage object is translated into a byte array
// and vice versa (using ToByteArray and ParseMessage methods)
}
I hope this helps,
Regards,
精彩评论