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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T04:56:12+00:00 2026-05-19T04:56:12+00:00

I’m building a simple tcp/ip chat program and I’m having difficulty sending messages separately.

  • 0

I’m building a simple tcp/ip chat program and I’m having difficulty sending messages separately. If for example I send two messages and both have content larger than the buffer which can hold 20 characters, 20 characters of the first message is sent and then 20 characters of the next message is sent and then the the rest of the first message and then the rest of the last message. So when I parse and concatenate the strings I get two messages, the beginning of the first message and the beginning of the second and the end of the first and end of the second, respectively. I want to know how to send a message, and queue the next messages until the first message has already been sent. As a side note I’m using asynchronous method calls and not threads.

My code:

Client:

protected virtual void Write(string mymessage)
{


               var buffer = Encoding.ASCII.GetBytes(mymessage);
               MySocket.BeginSend(buffer, 0, buffer.Length, 
SocketFlags.None,EndSendCallBack, null);

               if (OnWrite != null)
               {
                   var target = (Control) OnWrite.Target;
                   if (target != null && target.InvokeRequired)
                   {
                       target.Invoke(OnWrite, this, new EventArgs());
                   }
                   else
                   {
                       OnWrite(this, new EventArgs());
                   }
               }
        }

and the two calls that get mixed:

 client.SendMessage("CONNECT",Parser<Connect>.TextSerialize(connect));
  client.SendMessage("BUDDYLIST","");

and finally the read function (I use a number at the beginning of every message to know when the message ends surround by brackets):

private void Read(IAsyncResult ar)
        {

            string content;
            var buffer = ((byte[]) ar.AsyncState);
            int len = MySocket.EndReceive(ar);
            if (len > 0)
            {
                string cleanMessage;
                content = Encoding.ASCII.GetString(buffer, 0, len);
                if (MessageLength == 0)
                {
                    MessageLength = int.Parse(content.Substring(1, content.IndexOf("]", 1) - 1));
                    cleanMessage = content.Replace(content.Substring(0, content.IndexOf("]", 0) + 1), "");
                }
                else
                    cleanMessage = content;

                if(cleanMessage.Length <1)
                {
                    if(MySocket.Connected)
                        MySocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Read), buffer);
                    return;
                }

                MessageLength = MessageLength > cleanMessage.Length? MessageLength - cleanMessage.Length : 0;
                amessage += cleanMessage;

                if(MessageLength == 0)
                {
                    if (OnRead != null)
                    {
                        var e = new CommandEventArgs(this, amessage);
                        Control target = null;
                        if (OnRead.Target is Control)
                            target = (Control)OnRead.Target;
                        if (target != null && target.InvokeRequired)
                            target.Invoke(OnRead, this, e);
                        else
                            OnRead(this, e);
                    }
                    amessage = String.Empty;
                }
                MySocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Read), buffer);
                    return;
            }
        }
  • 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-05-19T04:56:12+00:00Added an answer on May 19, 2026 at 4:56 am

    TCP do not guarantee that you will receive your entire message in one read. Therefore you need to be able to detect where a message starts and where it ends.

    You normally do that by adding some special characters at the end of the message. Or use a length header before the actual message.

    You normally do not need to use BeginSend in a client. Send should be fast enough and will also reduce complexity. Also, I usually do not use BeginSend in servers either unless the server should be really performant.

    Update

    The actual socket implementation will never ever mix your messages, only your code can do that. You cannot send a message by calling multiple sends, since then your messages will be mixed if your application is multi threaded.

    In other words, this will not work:

    _socket.BeginSend(Encoding.ASCII.GetBytes("[" + message.Length + "]"))
    _socket.BeginSend(Encoding.ASCII.GetBytes(message));
    

    You have to send everything with one send.

    Update 2

    Your read implementation do not take into account that two messages can come in the same Read. It’s most likely that that’s the cause to your mixed messages.

    If you send:

    [11]Hello world
    [5]Something else
    

    They can arrive as:

    [11]Hello World[5]Some
    thing else
    

    In other words, part of the second message can arrive in the first BeginRead. You should always build a buffer with all received contents (use StringBuilder) and remove the handled parts.

    Pseudo code:

    method OnRead
        myStringBuilder.Append(receivedData);
        do while gotPacket(myStringBuilder)
            var length = myStringBuilder.Get(2, 5)
            if (myStringBuilder.Length < 7 + length)
               break;
    
            var myMessage = myStringBuilder.Get(7, length);
            handle(myMessage);
    
            myStringBuilder.Remove(0, 7+length);
        loop
    end method
    

    Do you see what I’m doing? I’m always appending the stringbuilder with the received data and then remove complete messages. I’m using a loop since multiple messages can arrive at once.

    • 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
We're building an app, our first using Rails 3, and we're having to build
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
Seemingly simple, but I cannot find anything relevant on the web. What is the
i got an object with contents of html markup in it, for example: string
I am writing an app with both english and french support. The app requests

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.