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

时间:2022-05-27 04:04:45

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