So I’ve started to muck around with sockets and asynchronously reading from them.
First question is what is the difference between this:
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, new AsyncCallback(ReadCallback), readResult);
and
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, ReadCallback, readResult);
Also, given this as my callback function, why did the example I read have a try/catch around the whole thing, surely you only need a try/catch around the socket.EndReceive() call?
public void ReadCallback(IAsyncResult ar)
{
try
{
var readResult = (SocketReadResult)ar.AsyncState;
var socket = readResult.Socket;
int bytesRead = socket.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
readResult.Text.Append(Encoding.ASCII.GetString(readResult.Buffer, 0, bytesRead));
// Get the rest of the data.
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, new AsyncCallback(ReadCallback), readResult);
}
else
{
var newRead = new SocketReadResult(socket);
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, new AsyncCallback(ReadCallback), newRead);
// All the data has arrived; put it in response.
if (readResult.Text.Length > 1) ((IMessageSender)this).RouteMessage(this, new MessageString(readResult.Text.ToString()));
}
}
catch (Exception e)
{
// TODO: manage this exception.
}
}
public struct SocketReadResult
{
StringBuilder Text;
Socket Socket;
byte[] Buffer;
public const int BufferSize = 1024;
public SocketReadResult(Socket s)
{
Socket = s;
Buffer = new byte[BufferSize];
Text = new StringBuilder();
}
}
Last of all, should you wish to gracefully close the listener after you have called socket.BeginReceive(), what functions do you call and how is it managed?
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, new AsyncCallback(ReadCallback), readResult);and
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, ReadCallback, readResult);both are the same thing, its same thing as