chronoxor / NetCoreServer

Ultra fast and low latency asynchronous socket server & client C# .NET Core library with support TCP, SSL, UDP, HTTP, HTTPS, WebSocket protocols and 10K connections problem solution
https://chronoxor.github.io/NetCoreServer
MIT License
2.63k stars 550 forks source link

Serialize and Deserialze #280

Open tharwat202020 opened 8 months ago

tharwat202020 commented 8 months ago

i want to send model as serialized the de serialize it after receive do you have any way

chronoxor commented 8 months ago

Yes, it possible to do with a help of FBE. Please see the example:

tharwat202020 commented 8 months ago

thanks for the answer but really i could not use it to send my models in the method of send(object); would you please help me with this to show me a simple example

chronoxor commented 8 months ago

You can serialize your data and send byte buffer using Send()/SendAsyc() methods in every TcpSession/SslSession/WsSession and TcpClient/SslClient/WsClient:

        public virtual long Send(byte[] buffer);
        public virtual long Send(byte[] buffer, long offset, long size);
        public virtual long Send(ReadOnlySpan<byte> buffer);

        public virtual long SendAsync(byte[] buffer);
        public virtual long SendAsync(byte[] buffer, long offset, long size);
        public virtual long SendAsync(ReadOnlySpan<byte> buffer);

SendAsync() will not block you, it will store data in send buffer and send later asynchronously.

Sample code to serialize/deserialize will be something like this:

public class MyClass {

   public int Id { get; set; }
   public string Name { 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 MyClass Desserialize(byte[] data) {
      MyClass result = new MyClass();
      using (MemoryStream m = new MemoryStream(data)) {
         using (BinaryReader reader = new BinaryReader(m)) {
            result.Id = reader.ReadInt32();
            result.Name = reader.ReadString();
         }
      }
      return result;
   }
}