使用Socket对序列化数据进行传输(基于C#)

客户端代码

[Serializable] // 表示该类可以被序列化
class Person
{
public string name;

public void HI()
{
Debug.Log(name);
}
}

public class NewSocketClient : MonoBehaviour {

void Start () {

Person p = new Person();
p.name = "Lz";
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

IPEndPoint point = new IPEndPoint(IPAddress.Parse("10.6.0.78"), 5684);
BinaryFormatter bf = new BinaryFormatter(); //创建序列化对象
client.Connect(point); //连接服务器

MemoryStream ms = new MemoryStream(); //创建内存流对象
bf.Serialize(ms, p); //将p序列化到内存流中

client.Send(ms.GetBuffer(),(int)ms.Length,SocketFlags.None);// 发送,长度为内存流中数据的长度


}
}

 

服务器代码

[Serializable] // 表示该类可以被序列化
class Person
{
public string name;

public void HI()
{
Debug.Log(name);
}
}

public class NewSocketServer : MonoBehaviour
{

Socket server_Socket;

void Start()
{
server_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

IPEndPoint point = new IPEndPoint(IPAddress.Any, 5684);

server_Socket.Bind(point);

server_Socket.Listen(10);

Thread acThread = new Thread(AcThread);

acThread.Start();
}


void AcThread()
{

Socket clientSocket = server_Socket.Accept(); //等待客户端连接

byte[] buffer = new byte[1024 * 1024];

int len = clientSocket.Receive(buffer);

MemoryStream memory = new MemoryStream();

BinaryFormatter bf = new BinaryFormatter();

memory.Write(buffer, 0, len);
memory.Flush();
memory.Position = 0;

Person p = bf.Deserialize(memory) as Person;
p.HI();

}


}

 

posted @ 2018-03-03 16:10  吃豆人  阅读(2155)  评论(0编辑  收藏  举报