0

Ok, so here is my problem... basically i made a code and i implemented a timer in it .. IF i run the "client" that sends data to the server and the timer is active, the messages stack if i want to send them very fast.

Example: Instead of:

"Hello"

I get:

"HelloHelloHelloHelloHelloHelloHelloHelloHello" stacked up if i want to send them very very fast... 1 milisecond lets say.

Is there a way to fix it without neceserally splitting them when the server gets the info? I`ll not give the recieve code as that works.. here is the problem:

 private void sends()
{
    if (serverSocket.Connected)
    {
        send = textBox2.Text;
        byte[] buffer = Encoding.ASCII.GetBytes(send);
        serverSocket.Send(buffer);
    }
}
private int s = 0;
private string send = string.Empty;
void Sendata(Socket socket, string stf)
{
    byte[] data = Encoding.ASCII.GetBytes(stf);
    socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);

}
private void SendCallback(IAsyncResult AR)
{
    Socket socket = (Socket)AR.AsyncState;
    socket.EndSend(AR);
}
private void button3_Click(object sender, EventArgs e)
{
   // timer1.Start();
    //Thread send = new Thread(new ThreadStart(sends));
   // send.Start(); 
    for (int i = 0; i < 50000; i++)
    {
         if (serverSocket.Connected)
    {
        send = textBox2.Text;
        Sendata(serverSocket, send);
    }
    }

}
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
KenTavur
  • 3
  • 5

1 Answers1

0

You need a way to delineate messages. Maybe send a newline after each message unless you need to be able to send newlines as part of the message. If that's the case, you could prefix each message with its length. Then receiving end would first parse the length and then wait for that many bytes before considering the message complete. This way, multiple messages could be sent in one big push and the receiving end would just parse them up by length.

itsme86
  • 19,266
  • 4
  • 41
  • 57
  • it's the same like if i split it ! – KenTavur Nov 17 '15 at 17:29
  • @KenTavur you need to understand that the underlying mechanism isn't message-based. It's a stream. It could even very well send a single "Hello" message split up. The receiver mind end up receiving "He" and then "llo" in a later read. You need to control your data. – itsme86 Nov 17 '15 at 17:32