Skip to content

Instantly share code, notes, and snippets.

@strich
Created July 9, 2014 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save strich/775170b49ed395e835f5 to your computer and use it in GitHub Desktop.
Save strich/775170b49ed395e835f5 to your computer and use it in GitHub Desktop.
public class Test {
private static List<Tuple<Protocol, int>> PortMapRequirements = new List<Tuple<Protocol, int>>();
private static bool _timeOutFinished = false;
private static List<Task> _portMapStatus = new List<Task>();
public static void Initialize() {
PortMapRequirements.Add(new Tuple<Protocol, int>(Protocol.Udp, 27015));
PortMapRequirements.Add(new Tuple<Protocol, int>(Protocol.Udp, 27016));
//PortMapRequirements.Add(new Tuple<Protocol, int>(Protocol.Tcp, 27015));
//PortMapRequirements.Add(new Tuple<Protocol, int>(Protocol.Tcp, 27016));
//NatUtility.TraceSource.Switch.Level = SourceLevels.All;
//NatUtility.TraceSource.Listeners.Add(ccl);
NatUtility.PortMapper = PortMapper.Upnp;
NatUtility.DeviceFound += DeviceFound;
NatUtility.DiscoveryTimedout += DiscoveryTimedout;
NatUtility.DiscoveryTimeout = 10000; // Seconds // TODO make this smaller once the slow port map issue is fixed.
NatUtility.ReleaseOnShutdown = false;
NatUtility.AutoRenewMappings = false;
NatUtility.Initialize();
NatUtility.StartDiscovery();
}
public static bool IsFinished() {
//if(!_timeOutFinished)
// return false;
// The portmap tasks seem to appear completed when they're really not.
foreach (var portMapStatus in _portMapStatus) {
if (portMapStatus.IsCompleted == false)
return false;
}
return true;
}
private static async void DeviceFound(object sender, DeviceEventArgs args) {
var device = args.Device;
foreach (var portMap in PortMapRequirements) {
var protocol = portMap.Item1;
var port = portMap.Item2;
var lifetime = 0; //8*60*60*1000; // 8 hours
var description = GameManager.GameName;
try {
_portMapStatus.Add(device.DeletePortMapAsync(new Mapping(protocol, port, port, lifetime, description)));
} catch {}
try {
_portMapStatus.Add(device.CreatePortMapAsync(new Mapping(protocol, port, port, lifetime, description)));
} catch {}
}
}
static void DiscoveryTimedout(object sender, DiscoveryTimeoutEventArgs e) {
_timeOutFinished = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment