在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;
}
}

 

用戶端代碼:
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)
{

 

}
}
}
服務端代碼:
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 + "退出");
}
}
}
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()