分享

C# socket通信传对象,用xml序列化和反序列化

 昵称10504424 2013-05-08

 

在wince平台下不能BinaryFormatter类来序列化对象,可以用xml来序列化对象,储存在内存流MemoryStream中。要注意MemoryStream的Position属性,在读的时候要设置为0。例子如下:

对象类:

复制代码
/// <summary>
///
/// </summary>
[XmlRoot("GatherData")]
public class GatherData
{
/// <summary>
/// 数据
/// </summary>
[XmlArray("Data")]
public string[] Data
{
get;
set;
}
/// <summary>
///
/// </summary>
[XmlElement("ModuleSht")]
public string ModuleSht
{
get;
set;
}
}
复制代码

客户端:

View Code
复制代码
public class SocketClient
{
/// <summary>
/// 发送数据线程
/// </summary>
        Thread mThread;
GatherData data;
public SocketClient()
{
mThread = new Thread(new ThreadStart(OnDataSend));
mThread.IsBackground = true;
mThread.Start();
}
/// <summary>
/// 发送采集数据
/// </summary>
private void OnDataSend()
{
try
{
Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ie = new IPEndPoint(IPAddress.Parse("172.16.78.112"), 60000);//服务器的IP和端口
try
{
newclient.Connect(ie);
}
catch (SocketException e)
{
}
data= new GatherData() { State = MsgSendState.start, Data = new string[] { "1", "2", "3" }, ModuleSht = "KYPLC" };
MemoryStream stream = new MemoryStream();
XmlSerializer se = new XmlSerializer(typeof(GatherData));
se.Serialize(stream, data);
stream.Flush();
byte[] buffer = new byte[stream.Length];//一次性发送(如果设定为固定值要循环多次发送)
stream.Position = 0;  //将流的当前位置重新归0,否则Read方法将读取不到任何数据\
while (stream.Read(buffer, 0, buffer.Length) > 0)
{
newclient.Send(buffer); //从内存中读取二进制流,并发送
                }
newclient.Shutdown(SocketShutdown.Both);
newclient.Close();
GC.Collect();
}
catch (Exception ex)
{
}
}
}
复制代码

服务端:

View Code
复制代码
 public class ClientSocket
{
const int BufferSize = 1024; static string path = @"E:\";
MemoryStream streams = new MemoryStream();
public object oSocket;
public void myClient()
{
Socket clientSocket = (Socket)oSocket;
string clientName = clientSocket.RemoteEndPoint.ToString();
XmlSerializer se = new XmlSerializer(typeof(GatherData));
try
{
while (true)
{
byte[] buffer = new byte[clientSocket.Available];
int count = clientSocket.Receive(buffer);
if(count==0)
break;
MemoryStream stream=new MemoryStream(buffer);
stream.WriteTo(streams);
string str = Encoding.UTF8.GetString(buffer);
}
streams.Position = 0;//读内存流的起始位置,不为0会出错;
GatherData data = se.Deserialize(streams) as GatherData;
}
catch(Exception ex)
{
Console.WriteLine("客户:" + clientName + "退出");
}
}
}
复制代码

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多