我正在尝试使用 Socket.BeginReceive(...) 和 Socket.EndReceive(...) 作为我的 UDP 数据包接收器客户端。它按预期接收和处理数据包,但是,当我希望取消和关闭套接字时,我实现的 Close() 函数在 Socket.EndReceive(...) 上退出。我假设线程上引发了异常,但我无法弄清楚如何捕获异常以查看问题所在。我之前使用过 Socket.EndReceive(...),而 SocketError 返回成功。这是一些代码,显示了我如何使用套接字。
更新代码
void _startReceiving()
{
_buffer = new byte[Marshal.SizeOf(typeof(EthernetShare.Message))];
_receiveResult = _udpSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, messageProcessor, null);
}
private void messageProcessor(IAsyncResult result)
{
int packetSize = _udpSocket.EndReceive(result);
if (packetSize == _buffer.Length)
{
byte[] packet = _buffer;
IAsyncResult asyncResult = result;
_startReceiving();
OnMessageReceieved(_buffer.ToStruct<DataStreamingMessage>());
}
}
public void Stop()
{
_continue = false;
SocketError error;
try
{
int tmp = _udpSocket.EndReceive(_receiveResult, out error);
}
catch (Exception)
{
throw;
}
_udpSocket.Close();
}
旧代码
private Socket _udpSocket;
private byte[] _buffer;
private IAsyncResult _receiveResult;
void _startReceiving()
{
byte[] buffer = new byte[Marshal.SizeOf(typeof(EthernetShare.Message))];
_receiveResult = _udpSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, messageProcessor, null);
//_receiveResult = _udpSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, messageProcessor, _continue);
}
private void messageProcessor(IAsyncResult result)
{
//if ((bool)result.AsyncState && result.IsCompleted)
if (result.IsCompleted)
{
_buffer = new byte[Marshal.SizeOf(typeof (EthernetShare.Message))];
//_receiveResult = _udpSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, messageProcessor, _continue);
_receiveResult = _udpSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, messageProcessor, null);
}
}
public void Stop()
{
_continue = false;
SocketError error;
try
{
int tmp = _udpSocket.EndReceive(_receiveResult, out error);
}
catch (Exception)
{
throw;
}
_udpSocket.Close();
}