MessageBase.Serialize C# (CSharp) Method

Serialize() public method

public Serialize ( ) : byte[]
return byte[]
        public byte[] Serialize()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                using (DeflateStream ds = new DeflateStream(stream, CompressionMode.Compress, true))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(ds, this);
                    ds.Flush();
                }
                byte[] bytes = stream.GetBuffer();
                byte[] bytes2 = new byte[stream.Length];
                Buffer.BlockCopy(bytes, 0, bytes2, 0, (int)stream.Length);

Usage Example

    // Broadcast data to all clients
    public void Broadcast(MessageBase msg)
    {
        try
        {
            // Serialize the message
            byte[] bytes = msg.Serialize();

            // Process all clients
            foreach (Socket client in clients)
            {
                try
                {
                    // Send the message
                    if (client.Connected)
                    {
                        client.BeginSend(bytes, 0, bytes.Length, 0, SendCallback, client);
                    }
                    else
                    {
                        HandleClientDisconnect(client);
                    }
                }
                catch (SocketException)
                {
                    HandleClientDisconnect(client);
                }
            }
        }
        catch (Exception e)
        {
            // Serialization error
            Console.WriteLine(e.ToString());
        }
    }
All Usage Examples Of MessageBase::Serialize