首页 > Windows开发 > 详细

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

时间:2018-03-03 17:32:18      阅读:302      评论:0      收藏:0      [点我收藏+]

客户端代码

[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();

}


}

 

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

原文:https://www.cnblogs.com/what-lee/p/8496966.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!