Recently, when I tested the communication module, I found that the data sent from the new Android platform was not received by the server. Later I found that some data types in java are different from those in C, for example, the byte value in C # ranges from 0 ~ 255, while in Java, it corresponds to-128 ~ 127, so there is always a problem with the binary stream directly serialized according to the communication protocol. Considering this, Joson is serialized to the server at the Android end, and the data received by the server is deserialized and converted to an object. At the same time, when the server sends data, it is converted to the Joson format and serialized as a binary stream to the Android end.
I will not talk much about it. Go to the Code:
// Binary transfer in Joson format is converted to an object
Public static T JosonDeSerializer <T> (byte [] buffer, int length)
{
Try
{
String mTextReceived = Encoding. UTF8.GetString (buffer, 0, length );
// Convert the obtained Joson string to a data package class
SocketDataPack sdp = GetSocketDataPackFromString (mTextReceived );
MemoryStream stream = new MemoryStream ();
BinaryFormatter formatter = new BinaryFormatter ();
// Serialize data packets
Formatter. Serialize (stream, sdp );
Stream. Position = 0;
Stream. Flush ();
// Convert to object
Object obj = formatter. Deserialize (stream );
If (obj = null)
{
Return default (T );
}
Return (T) obj;
}
Catch (Exception ex)
{
Throw ex;
}
}
// Convert an object to a binary stream in the Joson format
Public static byte [] JosonSerializer (object input)
{
Try
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer ();
String strSocketDataPack = jsonSerializer. Serialize (input );
Byte [] buffer = Encoding. UTF8.GetBytes (strSocketDataPack );
Return buffer;
}
Catch (Exception ex)
{
Throw ex;
}
}
/// <Summary>
/// Convert a Json string to a specified data package class
/// </Summary>
/// <Param name = "context"> </param>
/// <Returns> </returns>
Private static SocketDataPack GetSocketDataPackFromString (string context)
{
Try
{
SocketDataPack sdp = new SocketDataPack ();
Context = context. replace ("{",""). replace ("[",""). replace ("]", ""). replace ("}",""). replace ("\"",""). replace ("\ 0 ","");
String [] str = context. Split (',');
For (int I = 0; I <str. Length; I ++)
{
String [] str2 = str [I]. Split (':');
Switch (str2 [0])
{
Case "Length ":
Sdp. Length = Convert. ToInt16 (str2 [1]);
Break;
Case "Head ":
Sdp. Head = Convert. ToByte (str2 [1]);
Break;
// The data package type is omitted.
...
Case "Status ":
Sdp. Status = Convert. ToByte (str2 [1]);
Break;
Case "Tail ":
Sdp. Tail = Convert. ToByte (Convert. ToInt16 (str2 [1]);
Break;
}
}
Return sdp;
}
Catch (Exception ex)
{
Throw ex;
}
}
From weizhiai12's column