Search code examples
c#socketsserializationdeserializationbinaryformatter

binary formatter deserialize from memory stream freezing


I am trying to do a client-server application that communicate through sockets and their messages are serialez and deserialised using BinaryFormatter. My code is freezing and does absolutely nothing when reaching deserialize, and I don't understand why since I have no exception. I also can not step into with debugger, everything is freezing. This is my code:

 public class Serializer
    {
        public static MemoryStream ToStream(object obj)
        {
            var stream = new MemoryStream();
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, obj);
            return stream;
        }

        public static object FromStream(MemoryStream stream)
        {
            Console.WriteLine("Starting from stream");
            var formatter = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin);
            object rez = formatter.Deserialize(stream); //NEVER GOES OVER THIS
            Console.WriteLine("Starting deserialization" + rez);
            return formatter.Deserialize(stream);
        }
    }
public class Connection
    {
        private Socket socket;
        public Connection(Socket socket)
        {
            this.socket = socket;
            Console.WriteLine($"Connected to client: {socket.RemoteEndPoint}");
            Task.Factory.StartNew(() => Execute(socket));
        }

        private void Execute(Socket socket)
        {
            while (true)
            {
                var buffer = new byte[2048];
                var bytesCount = socket.Receive(buffer);
                if(bytesCount != 0)
                {
                    var msgReceived = (Message)Serializer.FromStream(new MemoryStream(buffer, 0, buffer.Length));
                    Console.WriteLine($"Received msg: {msgReceived.Content}");
                }
               /* var msg = new Message { Content = "Hello World2!" };
                Console.WriteLine($"Sending msg with content: {msg.Content}");
                MemoryStream stream = Serializer.ToStream(msg);
                var bytesSent = socket.Send(stream.GetBuffer());*/

                Console.WriteLine("Trying again");
                Thread.Sleep(500);
            }
        }

client code:

  var host = Dns.GetHostEntry("localhost");
            var ipAddress = host.AddressList.First();
            var serverEndpoint = new IPEndPoint(ipAddress, 9000);

            Socket serverSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Connect(serverEndpoint);

            Console.WriteLine($"Successfully connected to server on: {serverSocket.RemoteEndPoint}");

            while (true)
            {
                var msg = new Message { Content = "Hello World!" };
                Console.WriteLine($"Sending msg with content: {msg.Content}");
                MemoryStream stream = Serializer.ToStream(msg);
                var bytesSent = serverSocket.Send(stream.GetBuffer());
                Console.WriteLine("Waiting to receive");

                var buffer = new byte[2048];
                int bytesReceived = serverSocket.Receive(buffer);
                if (bytesReceived != 0)
                {
                    var receivedMessage = (Message)Serializer.FromStream(new MemoryStream(buffer));
                    Console.WriteLine($"Received message: {receivedMessage.Content}");
                }

                Console.WriteLine("Received done");

            }

server code :

var host = Dns.GetHostEntry("localhost");
            var ipAddress = host.AddressList.First();
            var localEndPoint = new IPEndPoint(ipAddress, 9000);
            var serverSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(localEndPoint);
            serverSocket.Listen(1);

            while (true)
            {
                Console.WriteLine("Waiting for client");
                Socket clientSocket = serverSocket.Accept();
                var connection = new Connection(clientSocket);
            }

I also checked the byteCount and they are arriving to the server, also the buffer is not empty, I don't understand why deserialize does nothing..


Solution

  • You call Deserialize twice, I think problem here:

    object rez = formatter.Deserialize(stream); //NEVER GOES OVER THIS
    Console.WriteLine("Starting deserialization" + rez);
    return formatter.Deserialize(stream);
    

    I think you can use methods like that:

        private byte[] SerializeMessage(Message msg)
        {
            var formatter = new BinaryFormatter();
            byte[] buf;
            using (MemoryStream stream = new MemoryStream())
            {
                formatter.Serialize(stream, msg);
                buf = new byte[stream.Length];
                return stream.ToArray();
            }
        }
    
         private Message DeserializeMessage(byte[] buff)
         {
                var formatter = new BinaryFormatter();
                ConnectingMessage msg;
                using (Stream stream = new MemoryStream(buff))
                {
                    msg = formatter.Deserialize(stream) as Message;
                }
    
                return msg;           
         }
    

    Also methods Send/Receive are synchronous, they block thread execution.

    The description of the asynchronous option is here https://learn.microsoft.com/en-us/dotnet/framework/network-programming/using-an-asynchronous-client-socket