Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8677577
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T20:29:39+00:00 2026-06-12T20:29:39+00:00

I’ve written an application which listens to a port and receives some packets,according to

  • 0

I’ve written an application which listens to a port and receives some packets,according to my customized protocol, the packets are either 49 byte to 1500 byte, which i can tell from data length in the packet. the way i should interpret and deal with data in 49 byte packets and bigger packets are different.

The problem is that when i receive packets less than 1374 byte everything is ok, but when the packet length gets more, i receive the following exception and i also lose 4 last bytes of my data(i’ve tested with a 1384byte packet and i lost the last 4 bytes)

Exception which is raised:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: startIndex

each 49 byte packet has 35 byte of data, and the data length of bigger packets are non-deterministic(because of compression).

i found out sometimes the last 4 bytes are in a seperate “bytes” and “result” variables,meaning they are being treated like new packets and are not being attached to the packet they belong to.

here’s the code for receiving data:

TcpClient Client = obj as TcpClient;
        EndPoint ep = Client.Client.RemoteEndPoint;
        List<Byte> result = new List<byte>();
        result.Capacity = 2000;
        try
        {


            NetworkStream stream = Client.GetStream();
            int i = 49;
            while ((i = stream.Read(bytes, 0,49)) != 0)
            {

                for (int id = 0; id < i; id++)
                {
                    result.Add(bytes[id]);
                }
//reading data length to determine packet length
                byte[] tmp = new byte[2];
                tmp = BitConverter.GetBytes(BitConverter.ToUInt16(result.ToArray(), 9));
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(tmp);
                }
                Int16 l = BitConverter.ToInt16(tmp, 0);
                if (l>35)
                {
                    stream.Read(bytes, result.Count, l - 35);
                    for (int id = 49; id <((l-35)+49); id++)
                    {
                        result.Add(bytes[id]);
                    }
                    if (this.TCPDataReceivedHandler != null)
                    {
                        this.TCPDataReceivedHandler(ep, result.Count, result.ToArray());
                        result.Clear();
                        Array.Clear(bytes, 0, 2000);
                        result.Capacity = 2000;
                    }
                }
                else
                {
                    if (this.TCPDataReceivedHandler != null)
                    {
                        this.TCPDataReceivedHandler(ep, result.Count, result.ToArray());
                        result.Clear();
                        Array.Clear(bytes, 0, 2000);
                        result.Capacity = 2000;
                    }
                }


            }
            System.Diagnostics.Debug.WriteLine("client Close");
            Client.Close();

        }
        catch (System.Exception ex)
        {
            throw ex;
        }
        finally
        {
            Client.Close();
            this.clients.Remove(Client);
        }

According to Greg Suggestion and my researches,i also tried using following method:

NetworkStream stream = Client.GetStream();
            int bytesread = 0, OffsetTemp = 0;

            while (stream.CanRead)
            {
                OffsetTemp = 0;

                bytesread += stream.Read(bytess, OffsetTemp, 11);
                OffsetTemp = OffsetTemp + 11;



                byte[] tmp = new byte[2];
                tmp = BitConverter.GetBytes(BitConverter.ToUInt16(bytess.ToArray(), 9));
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(tmp);
                }
                Int16 l = BitConverter.ToInt16(tmp, 0);

                bytesread += stream.Read(bytess, OffsetTemp++, 11 + l + 3);
                for (int id = 0; id < l + 14; id++)
                {
                    result.Add(bytess[id]);
                }

                if (this.TCPDataReceivedHandler != null)
                {
                    this.TCPDataReceivedHandler(ep, result.Count, result.ToArray());
                    result.Clear();
                    Array.Clear(bytess, 0, 2000);
                }

            }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T20:29:40+00:00Added an answer on June 12, 2026 at 8:29 pm

    When using TCP, you must keep in mind that the size of the data blocks you put in is not guaranteed to be the same size of data blocks you get out on the receiving side. TCP is a stream protocol, so it guarantees that the same bytes get to the other side in the same order as they were sent (if not, the socket connection will be reset). TCP does not maintain any kind of block boundaries between calls to send(), and blocks may be arbitrarily split or coalesced depending on network conditions.

    Your receiver must be prepared to handle receiving any amount of data from the calls to stream.Read(), but your code does not appear to do this. For example, correctly written receiver code should continue to work correctly even if stream.Read() receives only one byte at a time.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have an autohotkey script which looks up a word in a bilingual dictionary
I have an array which has BIG numbers and small numbers in it. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.