我正在努力解决这个问题,但它实际上是一个令人头疼的问题,套接字是为了与服务器建立两个连接,第二个是合法连接。我有这个方法,我附加到beginReceive方法的回调,虽然它调用Dispose两次?
通常它只调用一次,因为客户端与服务器建立2个连接,第二个是合法的,但似乎这个方法想要调用Dispose两次,这让我觉得有些不对劲,有人可以验证是否有什么错了吗?
private void OnIncomingData(IAsyncResult asyncResult)
{
int bytesReceived;
try
{
bytesReceived = _socket.EndReceive(asyncResult);
}
catch
{
Dispose();
return;
}
if (bytesReceived == 0)
{
Dispose();
return;
}
try
{
var packet = new byte[bytesReceived];
Array.Copy(_buffer, packet, bytesReceived);
var received = Encoding.UTF8.GetString(packet);
var packetData = JObject.Parse(received).ToFlatDictionary();
var incomingPacket = new IncomingPacket(packetData);
CoreUtilities.LogToConsole("Received packet: " + incomingPacket.Id + "\n\n" + received);
if (_session.PacketProvider.PacketEvents.TryGetValue(incomingPacket.Id, out var packetEvent))
{
packetEvent.Invoke(_session, incomingPacket);
CoreUtilities.LogToConsole("Finished executing packet " + packetEvent.GetType().Name + " for " + incomingPacket.Id);
}
else
{
CoreUtilities.LogToConsole("Failed to execute unknown incoming packet: " + incomingPacket.Id);
}
}
catch
{
Dispose();
}
finally
{
try
{
_socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, OnIncomingData, _socket);
}
catch
{
Dispose();
}
}
}