C# .Net Socket.Send Bug?

M

Matt

Hi, I've got a C# client/service application using a Socket object to
communicate. I have a socket bug that I can't solve without
kludged-code. Does anyone know a more elegant solutions? Is this a
known bug with the .NET Socket object?

Under high stress data sending, I occasionally receive duplicate data
on the server which really throws a wrench into the system. The
duplicate data I receive is always part of the tail end of the last
message sent.

Example:
Message 1: FirstMessage
Message 2: SecondMessage
Message 3: ssage (DUPLICATE BUG!)
Message 4: FourthMessage

I need to eliminate this problem. The only solution I have that works
is to add a Thread.Sleep(10) immediately after Socket.Send(buffer). If
I add that sleep, it works perfectly every time.

I have tried using a NetworkStream instead of a Socket, and I have
tried BeginSend/EndSend and they all demonstrate the exact same
problem.

This only happens when I am sending message very fast in a loop such
as:

for (int i=0; i < 1000; i++)
{
_socket.Send(buffer);
}

or

for (int i=0; i < 1000; i++)
{
// Async way
IAsyncResult asyncSend = _socket.BeginSend(regPackage, 0,
regPackage.Length, System.Net.Sockets.SocketFlags.None, null, null);
_socket.EndSend(asyncSend);
}

or

for (int i=0; i < 1000; i++)
{
SendData(_socket, regPackage);
}

public int SendData(TSSocket s, byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
while (total < size)
{
sent = s.Send(data, total, dataleft,
System.Net.Sockets.SocketFlags.None);
total += sent;
dataleft -= sent;
}
return total;
}


Again, the only solution that has worked for me is adding a
Thread.Sleep(10), or some other code that keeps the processor busy so
that the Send has time complete. I tried shorter wait times, but 1 or
2 doesn't give enough time, so I played it safer and choose 10.

The is a sample of how I've currently got it working:

for (int i=0; i < 1000; i++)
{
SendData(_socket, buffer);
Thread.Sleep(10);
}

HELP!
 
W

William Stacey [MVP]

Not sure, but are you trying to send the same buffer multiple times?
 
M

Matt

I'm really not trying to send the same buffer multiple times, that's
just an example of what I mean.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top