Just by looking at the code quickly, I suspect that you can stop registering your AsyncReads, because s.Available returns 0, I mean the following code
if (read > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read));
if (s.Available > 0)
{
s.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), state);
return;
}
}
To confirm, change the above to the following
if (read > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read));
SocketStateObject nextState = new SocketStateObject();
nextState.workSocket = s;
s.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), nextState);
}
This is not a complete code correction, but it will confirm if this is a problem. You need to make sure that you close sockets properly, etc.
Update
I also noticed that you are sending a socket as a state in a BeginSend call.
state.workSocket.BeginSend(answer, 0, answer.Length, SocketFlags.None, new AsyncCallback(Send), state.workSocket);
Send AsyncState SocketStateObject
SocketStateObject state = (SocketStateObject)iar.AsyncState;
InvalidCastExceptions, , catch. , , , , .