OutOfMemoryException when server reads message from client
<p>I'm making a client-server application, but when I try to login it throws an OutOfMemoryException, here is my code server-side:</p>

<pre><code>                byte[] buffer = new byte[4];
                requestCount = requestCount + 1;
                NetworkStream networkStream = clientSocket.GetStream();
                buffer = new byte[4];
                int readBytes = networkStream.Read(buffer, 0, 4);
                readBytes = networkStream.Read(buffer, 0, 4);
                if (readBytes == 0)
                    break;
                int MessageSize = BitConverter.ToInt32(buffer, 0);
                byte[] bufferreader = new byte[MessageSize]; &lt;- here the exception is thrown
                readBytes = networkStream.Read(bufferreader, 0, MessageSize);
                if (readBytes == 0)
                    break;
                dataFromClient = Encoding.ASCII.GetString(bufferreader);
                rCount = Convert.ToString(requestCount);
                serverResponse = R.Respond(dataFromClient);
                sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                networkStream.Write(sendBytes, 0, sendBytes.Length);
                networkStream.Flush();
</code></pre>

<p>and here is my client-side code:</p>

<pre><code>clientSocket.Connect("192.168.1.100", 666);
        SHA512Managed S = new SHA512Managed();
        byte[] result = S.ComputeHash(Encoding.UTF8.GetBytes(password));
        string epassword = Convert.ToBase64String(result);
        try
        {
            byte[] buffer = new byte[4];
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = Encoding.ASCII.GetBytes("authenticate|" + user + "$");
            buffer = new byte[4];
            buffer = BitConverter.GetBytes(outStream.Length);
            serverStream.Write(buffer, 0, 4);
            serverStream.Flush();
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
            byte[] inStream = new byte[10025];
            serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
            string returndata = Encoding.ASCII.GetString(inStream);
        }
        catch(Exception ex)
        {
            Toast.MakeText(l, ex.Message, ToastLength.Long).Show();
        }
        Toast.MakeText(l, "Logged In: " + epassword, ToastLength.Long).Show();
</code></pre>

<p>So basically the client first sends the length of the actual message to the server so it knows how much bytes it has to expect, but when i create a new buffer that will hold the message it throws the OutOfMemoryException,</p>

<p>Thanks in advance</p>