private void NetworkAcceptDataAsync(IAsyncResult result) { try { var container = (PacketDataContainer)result.AsyncState; var len = _socket.EndReceiveFrom(result, ref container.Remote); if (!_remotePackets.ContainsKey(container.Remote)) { if (len != _handshakeIn.Length || !container.ValidateBlock(_handshakeIn)) { return; } Logger.Info($"Received handshake packet from [/{container.Remote}], len: {len}"); try { Logger.Info($"Response auth success to [/{container.Remote}]"); var instanceRemoteState = new RemotePacketState(); _remotePackets.Add(container.Remote, instanceRemoteState); _handshakeOut[_handshakeOut.Length - 1] = instanceRemoteState.MagicByte; _socket.SendTo(_handshakeOut, container.Remote); } catch { ; } } var remoteState = _remotePackets[container.Remote]; // If user trying to send auth handshake again, response that all ok if (container.ValidateBlock(_handshakeIn)) { _handshakeOut[_handshakeOut.Length - 1] = remoteState.MagicByte; _socket.SendTo(_handshakeOut, container.Remote); return; } var magicByteRemote = container.Buffer[0]; if (magicByteRemote != remoteState.MagicByte) { Logger.Warn($"Invalid remote magic byte '{magicByteRemote}' instead of '{remoteState.MagicByte}' from [/{container.Remote as IPEndPoint}]"); return; } NetworkRemoteControl.AcceptPacket(remoteState, container); } catch (ObjectDisposedException) { ; } catch (Exception e) { Logger.Error("Accept data packet error", e); } finally { NetworkStartAcceptingData(); } }
public void SendPacket(NetPacket packet, PacketDataContainer dataContainer, RemotePacketState remoteState) { if (packet == null) { Logger.Warn("Trying to send empty packet!"); return; } var packetId = NetworkRemoteControl.FindPacketIdByType(packet.GetType()); if (packetId == null) { Logger.Debug($"Trying to send unknown packet {packet.GetType().FullName}"); return; } using (var ms = new MemoryStream()) { using (var bw = new BinaryWriter(ms)) { bw.Write((uint)packetId); packet.Write(new StreamWriter(ms), remoteState); _socket.SendTo(ms.GetBuffer(), dataContainer.Remote); } } }