最近在測試通訊模塊時,發現新增的Android平台發送過來的數據,服務器端總是收不到,後來發現java中數據類型有些和C#中的不一樣,比如C#中byte對應范圍是0~255,而Java中則對應的是-128~127,因此直接按照通訊協議傳序列化的二進制流總是出現問題。考慮到這一點在Android那一端才用Joson序列化發送到服務端,而在服務端對接收到的數據進行反序列化後轉化為對象。同時在服務端進行發送數據時,轉換為Joson格式後,序列化為二進制流發生給Android端。
廢話不多說了,上代碼:
//Joson格式的二進制流轉換為對象
public static T JosonDeSerializer<T>(byte[] buffer, int length)
{
try
{
string mTextReceived = Encoding.UTF8.GetString(buffer, 0, length);
//將獲取到的Joson格式字符串轉換為數據包類
SocketDataPack sdp = GetSocketDataPackFromString(mTextReceived);
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
//將數據包類序列化
formatter.Serialize(stream, sdp);
stream.Position = 0;
stream.Flush();
//轉換為對象
object obj = formatter.Deserialize(stream);
if (obj == null)
{
return default(T);
}
return (T)obj;
}
catch (Exception ex)
{
throw ex;
}
}
//對象轉換為Joson格式二進制流
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>
/// 將Json格式的字符串轉換為指定的數據包類
/// </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;
//中間的數據包類的類型省略
。。。
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;
}
}