请问 C# 通过 Socket 怎样发送json格式的字符串,求请教~!

2024-11-22 15:59:41
推荐回答(1个)
回答1:

///


/// 序列化
///

///
///
public static string getJsonStringByObject(object obj)
{
DataContractJsonSerializer serialier = new DataContractJsonSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
serialier.WriteObject(stream, obj);
byte[] dataBytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(dataBytes, 0, (int)stream.Length);
string msg = Encoding.UTF8.GetString(dataBytes);
return msg;
}
string jsonString = getJsonStringByObject(list);
byte[] buffer= Encoding.UTF8.GetBytes(jsonString)
NetworkStream netStream = client.GetStream(); //client是Socket连接
netStream.Write(buffer, 0, buffer.Length); //发送