在C#中如何将一个对象做为消息用Socket传输
在C#中如何将一个对象做为消息用Socket传输,
比如一个对象Message request在客户端通过Socket传给服务端,
服务器端再把它还原成Message,如何实现呢?
------解决方案--------------------using System;
using System.Collections.Generic;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Security.Permissions;
public class MyClass
{
[Serializable]
public class A{
public int intField;
public string strFiled;
}
public static void Main()
{
try{
//实例化类
A a=new A();
a.intField=100;
a.strFiled= "Hello world ";
//序列化
MemoryStream ms=new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, a);
byte[] bytes=ms.ToArray();
Console.WriteLine(BitConverter.ToString(bytes));
//移动到头部
ms.Position =0;
//反序列化,并显示
A b=formatter.Deserialize(ms) as A;
Console.WriteLine( "intField:{0} \t strFiled:{1} ",b.intField,b.strFiled);
}
catch(Exception e){
Console.WriteLine(e.ToString());
}
finally{
Console.WriteLine( "END ");
Console.Read();
}
}
}
========================运行结果
00-01-00-00-00-FF-FF-FF-FF-01-00-00-00-00-00-00-00-0C-02-00-00-00-3D-6F-75-74-70
-75-74-2C-20-56-65-72-73-69-6F-6E-3D-30-2E-30-2E-30-2E-30-2C-20-43-75-6C-74-75-7
2-65-3D-6E-65-75-74-72-61-6C-2C-20-50-75-62-6C-69-63-4B-65-79-54-6F-6B-65-6E-3D-
6E-75-6C-6C-05-01-00-00-00-09-4D-79-43-6C-61-73-73-2B-41-02-00-00-00-08-69-6E-74
-46-69-65-6C-64-08-73-74-72-46-69-6C-65-64-00-01-08-02-00-00-00-64-00-00-00-06-0
3-00-00-00-0B-48-65-6C-6C-6F-20-77-6F-72-6C-64-0B
intField:100 strFiled:Hello world
END