Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialize and Deserialze #280

Open
tharwat202020 opened this issue Jan 2, 2024 · 3 comments
Open

Serialize and Deserialze #280

tharwat202020 opened this issue Jan 2, 2024 · 3 comments

Comments

@tharwat202020
Copy link

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

@chronoxor
Copy link
Owner

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

@tharwat202020
Copy link
Author

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
Copy link
Owner

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;
   }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants