0

我有一个 C# 中的 UDP 客户端服务器应用程序,服务器将序列化对象发送到客户端。在服务器端对象被反序列化。现在我的问题是如何访问对象的字段或数据成员?任何建议或帮助将不胜感激。

谢谢瓦尼

这是发送对象的服务器代码。

namespace UDP_Client
{
[Serializable]
class SendObject
{
    public int a;
    public int b;
    public int c;
    public SendObject()
    {
        a = 0;
        b = 0;
        c = 0;
    }

}
class ClientSocket
{
    static void Main(string[] args)
    {

        SendObject obj= new SendObject();
        obj.a = 100;
        obj.b = 200;
        obj.c = 300;
        MemoryStream memorystream = new MemoryStream();
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(memorystream,obj);
        Send(obj.ToString());


    }
    static void Send(string Message)
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPAddress broadcast = IPAddress.Parse("127.0.0.1");
        byte[] sendbuffer = Encoding.ASCII.GetBytes(Message);
        IPEndPoint ep = new IPEndPoint(broadcast, 10000);
        s.SendTo(sendbuffer, ep);
        s.Close();

    }
}

}

这是接收来自服务器的对象的客户端。UdpClient 监听器 = new UdpClient(listenPort); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);

                byte[] bytes = listener.Receive(ref groupEP);

                MemoryStream stream = new MemoryStream();
                BinaryFormatter formatter = new BinaryFormatter();
                stream.Seek(0, SeekOrigin.Begin);
                Object obj = (Object)formatter.Deserialize(stream);
                int val1 = obj.a;//This is what i want to do.
4

0 回答 0