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 8646245
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T12:45:27+00:00 2026-06-12T12:45:27+00:00

I’m having some issues when I really stress test my networking code. Essentially once

  • 0

I’m having some issues when I really stress test my networking code. Essentially once the socket is set up it calls this:

NetworkStream networkStream = mClient.GetStream();
networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);


private void ReadCallback(IAsyncResult result)
        {
            try
            {
                int read;
                NetworkStream networkStream;
                try
                {
                    networkStream = mClient.GetStream();
                    read = networkStream.EndRead(result);
                }
                catch
                {
                    return;
                }

                if (read == 0)
                {
                    //The connection has been closed.
                    return;
                }

                var readBuffer = (byte[])result.AsyncState;
                var readCount = readBuffer.Length;
                while (readCount < 4)
                {
                    readCount += networkStream.Read(readBuffer, 0, readBuffer.Length - readCount);
                }
                var length = BitConverter.ToInt32(readBuffer, 0);
                var messageBuffer = new byte[length];
                readCount = 0;
                while (readCount < length)
                {
                    readCount += networkStream.Read(messageBuffer, 0, messageBuffer.Length - readCount);
                }
                else
                {
                    RaiseMessageReceived(this, messageBuffer);
                }
                //Then start reading from the network again.
                readBuffer = new byte[4]; //may not need to reset, not sure
                networkStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, readBuffer);
            }
            catch(Exception)
            {
                //Connection is dead, stop trying to read and wait for a heal to retrigger the read queue
                return;
            }
        }

Then the below is my send methods

private byte[] GetMessageWithLength(byte[] bytes)
        {
            //Combine the msg length to the msg
            byte[] length = BitConverter.GetBytes(bytes.Length);
            var msg = new byte[length.Length + bytes.Length];
            Buffer.BlockCopy(length, 0, msg, 0, length.Length);
            Buffer.BlockCopy(bytes, 0, msg, length.Length, bytes.Length);
            return msg;
        }

public override bool Send(byte[] bytes)
        {
            lock (sendQueue)
            {
                sendQueue.Enqueue(bytes);
                Interlocked.Increment(ref sendQueueSize);
            }
            if (!mClient.Connected)
            {
                if (Connect())
                {
                    RaiseConnectionChanged(this, true, Localisation.TCPConnectionEstablished);
                }
                else
                {
                    RaiseConnectionChanged(this, false, (bytes.Length > 0 ? Localisation.TCPMessageFailed : Localisation.TCPMessageConnectionLost));
                }
            }

            try
            {
                NetworkStream networkStream = mClient.GetStream();

                lock (sendQueue)
                {
                    if (sendQueue.Count == 0)
                    {
                        return true;
                    }
                    bytes = sendQueue.Dequeue();
                }
                var msg = GetMessageWithLength(bytes);
                //Start async write operation
                networkStream.BeginWrite(msg, 0, msg.Length, WriteCallback, null);
            }
            catch (Exception ex)
            {
                RaiseConnectionChanged(this, false, (bytes.Length > 0 ? Localisation.TCPMessageFailed : Localisation.TCPMessageConnectionLost));
            }
            return true;
        }

        /// <summary>
        /// Callback for Write operation
        /// </summary>
        /// <param name="result">The AsyncResult object</param>
        private void WriteCallback(IAsyncResult result)
        {
            try
            {
                NetworkStream networkStream = mClient.GetStream();
                while (sendQueue.Count > 0)
                {
                    byte[] bytes;
                    lock (sendQueue)
                    {
                        if (sendQueue.Count == 0)
                        {
                            break;
                        }
                        bytes = sendQueue.Dequeue();
                    }
                    var msg = GetMessageWithLength(bytes);
                    networkStream.Write(msg, 0, msg.Length);
                    Interlocked.Decrement(ref sendQueueSize);
                }
                networkStream.EndWrite(result);
                mLastPacketSentAt = Environment.TickCount;
                Interlocked.Decrement(ref sendQueueSize);
            }
            catch (Exception ex)
            {
                RaiseConnectionChanged(this, false, Localisation.TCPMessageConnectionLost);
            }
        }

But yea, at some point when I stress test the system (say 500 or so clients sending lots of messages at once), I notice maybe 1 packet in every 4 million to just not get recieved. I’m not sure if the issue lies in the sending or the recieving, which is why I have included both methods. However I will point out that if I choose to send another packet from the client, it still sends and receives correctly, so it is not just queued or something.

Can anyone see something I am missing?

  • 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-12T12:45:28+00:00Added an answer on June 12, 2026 at 12:45 pm

    The two read loops (e.g. while (readCount < length)) are buggy. You always read at offset zero. You should read at an ever-increasing offset.

    This lead to overwriting of already-read data.

    Also, I’m not sure if it is a good idea to mix synchronous and asynchronous reads. You lose the benefit of asynchronous code that way and still have to deal with callbacks and such. I think you should decide on one style and stick to it.

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

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have just tried to save a simple *.rtf file with some websites and
this is what i have right now Drawing an RSS feed into the php,
We're building an app, our first using Rails 3, and we're having to build
This could be a duplicate question, but I have no idea what search terms

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.