在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 + "退出"); } } }
|
|
来自: 昵称10504424 > 《C#》