简体   繁体   English

c#如何从socket接收和解析具有原始字段数组的对象

[英]c# How to recieve and parse object with arrays of primitive fields from socket

I'm new with .net(C#). 我是.net(C#)的新手。

I need to write an application which gets objects from socket and display it on screen. 我需要编写一个从套接字获取对象并在屏幕上显示它的应用程序。

The other application which send the messages is not c# (it's c++ if it's matter) 发送消息的另一个应用程序不是c#(如果有问题就是c ++)

The ICD of the objects is: 对象的ICD是:

int id;
char name[20];
short rates[5]
int lastGrades[10];
  1. How can I define this object in c# ? 如何在c#中定义此对象? (It seems that I cant define class with primitve array without using new operator) (似乎我不能使用primitve数组定义类而不使用new运算符)

I want to do somthing like that to get the message from socket and cast it to my MyObject class. 我想做类似的事情来从socket获取消息并将其转换为我的MyObject类。

somthing like: 像这样的东西:

byte b[] = new byte[100];
socket.Recvive(b);
MyObject myObject = ???cast??? b;
  1. How can I do it ? 我该怎么做 ?

Here is an example for you 这是一个例子

public class ICD {

   public int Id { get; set; }
   public string Name { get; set; }
   public short[5] Rates { get; set; }
   public int[5] Grades { get; set; }


   public byte[] Serialize() {
      using (MemoryStream m = new MemoryStream()) {
         using (BinaryWriter writer = new BinaryWriter(m)) {
            writer.Write(Id);
            writer.Write(Name);
         }
         return m.ToArray();
      }
   }

   public static ICD Desserialize(byte[] data) {
      ICD result = new ICD();
      using (MemoryStream m = new MemoryStream(data)) {
         using (BinaryReader reader = new BinaryReader(m)) {
            result.Id = reader.ReadInt32();
            result.Name = reader.ReadString();
         }
      }
      return result;
   }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM