• 使用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();

    }


    }

    本博客所有内容均为原创,转载请注明出处.
  • 相关阅读:
    压测mysql连接数
    OpenStack SR-IOV
    Scheduler 租户虚机到不同host
    Neutron 集成 DPDK
    Centos 7 密码重置
    win10优化
    Aria
    tomcat lb cluster
    Tomcat.md
    varnish.md
  • 原文地址:https://www.cnblogs.com/what-lee/p/8496966.html
Copyright © 2020-2023  润新知