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);
4

1 回答 1

0

如果您使用的是 .Net 3.5 或更高版本,我强烈建议您查看Windows Communication Foundation (wcf)。它只是您尝试通过网络执行的任何操作。

另一方面,如果您这样做纯粹是出于教育目的。看看这个链接。最好的办法是以更小的增量从流中读取数据,然后将该数据馈送到另一个流中。一旦您确定了一条消息所需的数据长度,您就可以将第二个流切断成一条消息。您可以设置一个外部循环,在其中检查可用字节并等待其值 > 0 以开始下一条消息。还应该注意,任何网络代码都应该在自己的线程上运行,以免阻塞 UI 线程。

于 2011-06-01T21:53:40.143 回答