打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

 

在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 + "退出");}}}

 

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Unity技术博客
Select模型 详解
C# TCP 客户端代码
译文:如何使用SocketAsyncEventArgs类(How to use the SocketAsyncEventArgs class)
[C# 网络编程系列]自定义Web服务器
Android socket高级用法(自定义协议和Protocol Buffer使用)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服