0

I've been learning C# by creating an app and i've hit a snag i'm really struggling with.

Basicly i have the code below which is what im using to read from a network stream I have setup. It works but as its only reading 1 packet for each time the sslstream.Read() unblocks. It's causes a big backlog of messages.

What im looking at trying to do is if the part of the stream read contains multiple packets read them all.

I've tried multiple times to work it out but i just ended up in a big mess of code.

If anyone could help out I'd appreciate it!

(the first 4bytes of each packet is the size of the packet.. packets range between 8 bytes and 28,000 bytes)

        SslStream _sslStream = (SslStream)_sslconnection;
        int bytes = -1;
        int nextread = 0;
        int byteslefttoread = -1;
        byte[] tmpMessage;
        byte[] buffer = new byte[3000000];
        do
        {
            bytes = _sslStream.Read(buffer, nextread, 8192);
           int packetSize = BitConverter.ToInt32(buffer, 0);
            nextread += bytes;
            byteslefttoread = packetSize - nextread;

            if (byteslefttoread <= 0)
            {
                int leftover = Math.Abs(byteslefttoread);
                do
                {
                    tmpMessage = new byte[packetSize];
                    Buffer.BlockCopy(buffer, 0, tmpMessage, 0, packetSize);

                    PacketHolder tmpPacketHolder = new PacketHolder(tmpMessage, "in");
                    lock (StaticMessageBuffers.MsglockerIn)
                    {
                        //puts message into the message queue.. not very oop... :S
                        MessageInQueue.Enqueue(tmpPacketHolder);
                    }
                }
                while (leftover > 0);

                Buffer.BlockCopy(buffer, packetSize , buffer, 0, leftover);
                byteslefttoread = 0;
                nextread = leftover;

            }

        } while (bytes != 0);
james
  • 1,031
  • 1
  • 15
  • 31

1 Answers1

0

If you are using .Net 3.5 or later I would highly suggest you look into Windows Communication Foundation (wcf). It will simply anything you are trying to do over a network.

On the other hand, if you are doing this purely for educational purposes. Take a look at this link. Your best bet is to read from the stream in somewhat smaller increments, and feed that data into another stream. Once you can identify the length of data you need for a message, you can cut the second stream off into a message. You can setup an outside loop where available bytes are being checked and wait until its value is > 0 to start the next message. Also should note, that any network code should be running on its own thread, so as to not block the UI thread.

Jay
  • 6,224
  • 4
  • 20
  • 23