Reputation: 4498
I have a desktop application written in C# that will communicate with an Android app. What is the easiest way to pass data between them over a tcp/ip connection? I'm less interested in performance, more interested in ease of implementation.
Upvotes: 0
Views: 805
Reputation: 1248
I naturally don't understand you by the meaning of ease of implementation
. But as I guessed, you should need these:
In [C#]:
//util function
public static void WriteBuffer(BinaryWriter os, byte[] array) {
if ((array!=null) && (array.Length > 0) && (array.Length < MAX_BUFFER_SIZE)) {
WriteInt(os,array.Length);
os.Write(array);
} else {
WriteEmptyBuffer(os);
}
}
//write a string
public static void WriteString(BinaryWriter os, string value) {
if (value!=null) {
byte[] array = System.Text.Encoding.Unicode.GetBytes(value);
WriteBuffer(os,array);
} else {
WriteEmptyBuffer(os);
}
}
In [Java] Android:
/** Read a String from the wire. Strings are represented by
a length first, then a sequence of Unicode bytes. */
public static String ReadString(DataInputStream input_stream) throws IOException
{
String ret = null;
int len = ReadInt(input_stream);
if ((len == 0) || (len > MAX_BUFFER_SIZE)) {
ret = "";
} else {
byte[] buffer = new byte[len];
input_stream.readFully(buffer);
ret = new String(buffer, DATA_CHARSET);
}
return (ret);
}
For further structural data, For e.g you want to send objects between C# and Java, please use XML Serialization in C#
and XML Parser in Java
. You can search for these on Internet; many examples are on Code Project website.
In Android part, you can use XStream library for ease of use.
Upvotes: 2