所以我开始使用套接字并异步读取它们。
第一个问题是这之间有什么区别:
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, new AsyncCallback(ReadCallback), readResult);
和
socket.BeginReceive(readResult.Buffer, 0, SocketReadResult.BufferSize, 0, ReadCallback, readResult);
另外,鉴于这是我的回调函数,为什么我阅读的示例对整个事情都有一个 try/catch,当然你只需要一个 try/catch 围绕socket.EndReceive()
调用?
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();
}
}
最后,您是否希望在调用后优雅地关闭侦听器,您调用socket.BeginReceive()
了哪些函数以及它是如何管理的?