In the code below, I make a call from Main()
to Receive()
, which in turn calls the Async BeginReceive()
, and completes receiving the data in a background thread.
The Problem: For the first read, BeginReceive is succesful and appends the StringBuilder. However, when called again, the if(bytesread>0)
condition is never reached and thus I never act on the data received.
I want BeginReceive to deal with more than one read, and (i think this is related with the threading) I would like for the Main()
function to be always listening for new COMMANDS from the client (not new connections, I'd like to keep the same Socket). Is this even possible?
Attempts At Solution: I added the ManualResetEvent in an attempt to stop the Main()
function from exiting prior to the Async reading going on in another thread.
Relevant Code in Main():
Receive(server); //await instructions from the client
done.WaitOne(); //This is a ManualResetEvent.
Console.ReadLine();
Method Definitions:
public static void Receive(Socket server)
{
try
{
SocketArgs sockargs = new SocketArgs();
sockargs.handler = server;
server.BeginReceive(sockargs.buffer, 0, sockargs.buffersize, 0, new AsyncCallback(ReceiveCallBack), sockargs);
}
catch
{
}
}
public static void ReceiveCallBack(IAsyncResult ia)
{
try
{
SocketArgs sockargs = (SocketArgs)ia.AsyncState;
Socket server = sockargs.handler;
int BytesRead = server.EndReceive(ia);
if (BytesRead > 0)
{
//Continue reading data.
sockargs.sb.Append(Encoding.ASCII.GetString(sockargs.buffer, 0, BytesRead));
MessageBox.Show(sockargs.sb.ToString());
server.BeginReceive(sockargs.buffer, 0, sockargs.buffersize, 0, new AsyncCallback(ReceiveCallBack), sockargs);
}
else
{ //Do stuff with sb.ToString()
done.Set();
}
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…