private void OnStart(int port, int wsPort, int minDesiredConnections, int maxConnections, int maxConnectionsPerAddress) { ListenerPort = port; MinDesiredConnections = minDesiredConnections; MaxConnections = maxConnections; MaxConnectionsPerAddress = maxConnectionsPerAddress; timer = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(0, 5000, Context.Self, new Timer(), ActorRefs.NoSender); if ((port > 0 || wsPort > 0) && localAddresses.All(p => !p.IsIPv4MappedToIPv6 || IsIntranetAddress(p)) && isUPnPDiscovered) { try { if (port > 0) { UPnP.ForwardPort(port, ProtocolType.Tcp, "Zoro"); } if (wsPort > 0) { UPnP.ForwardPort(wsPort, ProtocolType.Tcp, "Zoro WebSocket"); } } catch { } } if (port > 0) { tcp_manager.Tell(new Tcp.Bind(Self, new IPEndPoint(IPAddress.Any, port), options: new[] { new Inet.SO.ReuseAddress(true) })); } if (wsPort > 0) { ws_host = new WebHostBuilder().UseKestrel().UseUrls($"http://*:{wsPort}").Configure(app => app.UseWebSockets().Run(ProcessWebSocketAsync)).Build(); ws_host.Start(); } }
public void Shutdown() { _vncManager.StopVncServer(); if (_worker != null) { _worker.CancelAsync(); } if (_apiClient != null) { try { _apiClient.Unregister(new UnregisterRequest { ComputerName = ConfigManager.Data.ComputerName, GroupID = ConfigManager.Data.GroupId }); } catch {} _apiClient.Close(); } if (_relayManager != null) { _relayManager.Stop(); } if (_externalEP != null) { UPnP.RemoveMapping(_externalEP.Port); } }
public static async void LanGameOptionsMenuSystem(Control control, WndWindowMessage message, ControlCallbackContext context) { Logger.Trace($"Have message {message.MessageType} for control {control.Name}"); if (!await GameOptions.HandleSystemAsync(control, message, context)) { switch (message.MessageType) { case WndWindowMessageType.SelectedButton: switch (message.Element.Name) { case "LanGameOptionsMenu.wnd:ButtonBack": context.Game.SkirmishManager.Stop(); if (UPnP.Status == UPnPStatus.PortsForwarded) { await UPnP.RemovePortForwardingAsync(); } context.WindowManager.SetWindow(@"Menus\LanLobbyMenu.wnd"); break; default: Logger.Warn($"No callback for {message.Element.Name}"); break; } break; } } }
public void startServer() { UPnP.OpenFirewallPort("iRobot", UPnP.Protocol.TCP, 8080); string[] prefixes = { "http://+:8080/" }; // URI prefixes are required, // for example "http://contoso.com:8080/index/". if (prefixes == null || prefixes.Length == 0) { throw new ArgumentException("prefixes"); } // Create a listener. listener = new HttpListener(); // Add the prefixes. foreach (string s in prefixes) { listener.Prefixes.Add(s); } listener.Start(); bool keepListening = true; while (keepListening) { keepListening = handleRequest(listener); // TODO: display power status // Console.Out.WriteLine(); } listener.Stop(); }
void mWorkerForwarder_DoWork(object sender, DoWorkEventArgs e) { int port = (int)((object[])e.Argument)[0]; bool adding = (bool)((object[])e.Argument)[1]; try { if (!UPnP.CanUseUpnp) { e.Result = 0; return; } else { if (adding) { UPnP.ForwardPort(port, ProtocolType.Tcp, "MCForgeServer"); e.Result = 1; } else { UPnP.DeleteForwardingRule(port, ProtocolType.Tcp); e.Result = 3; } return; } } catch { e.Result = 2; return; } }
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { DialogResult dr = MessageBox.Show("Do you want to minimize the program instead of closing it?", "Exit or minified", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation); if (dr == DialogResult.Yes) { this.WindowState = FormWindowState.Minimized; hideToolStripMenuItemNotifyIcon.Text = "Show"; this.ShowInTaskbar = false; notifyIcon.BalloonTipIcon = ToolTipIcon.Info; notifyIcon.BalloonTipTitle = "CinaRAT is now minified"; notifyIcon.BalloonTipText = "CinaRAT still running in background." + Environment.NewLine + "If you want to close the program, right click the icon and choose close."; notifyIcon.ShowBalloonTip(5000); e.Cancel = true; } else if (dr == DialogResult.No) { ListenServer.Disconnect(); UPnP.DeletePortMap(Settings.ListenPort); notifyIcon.Visible = false; notifyIcon.Dispose(); Instance = null; } else if (dr == DialogResult.Cancel) { e.Cancel = true; } }
private static void PrintMappings() { Console.WriteLine("--Mappings Start--"); try { for (int i = 0;; i++) { try { var ret = UPnP.GetGenericPortMappingEntry(i); if (ret.Count == 0) { break; } Console.WriteLine(i); foreach (var e in ret) { Console.WriteLine(e); } Console.WriteLine(); } catch { break; } } } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("--Mappings End--"); }
void mWorkerForwarder_DoWork(object sender, DoWorkEventArgs e) { int tries = 0; int port = (int)((object[])e.Argument)[0]; bool adding = (bool)((object[])e.Argument)[1]; retry: try { tries++; if (!UPnP.Discover()) { e.Result = 0; } else if (adding) { UPnP.ForwardPort(port, ProtocolType.Tcp, Server.SoftwareName + "Server"); e.Result = 1; } else { UPnP.DeleteForwardingRule(port, ProtocolType.Tcp); e.Result = 3; } } catch { if (tries < 2) { goto retry; } e.Result = 2; } }
public static void Main() { if (UPnP.IsAvailable) { Console.WriteLine($"It worked! Local: {UPnP.LocalIP}, External:{UPnP.ExternalIP}"); } else { Console.WriteLine("It failed"); } PrintMappings(); const ushort port = 25000; Console.WriteLine($"IsOpen({Protocol.TCP},{port}) --> {UPnP.IsOpen(Protocol.TCP, port)}"); Console.WriteLine("Opening Port"); UPnP.Open(Protocol.TCP, port); Console.WriteLine("Opened"); Console.WriteLine($"IsOpen({Protocol.TCP},{port}) --> {UPnP.IsOpen(Protocol.TCP, port)}"); PrintMappings(); Console.ReadKey(); Console.WriteLine("Closing Port"); UPnP.Close(Protocol.TCP, port); Console.WriteLine("Closed"); }
static void Main() { //Program entrypoint IUPnPConfigFactory sinkfact = new SinkFactory(); IUPnPConfigFactory sourceFact = new SourceFactory(); UPnP sink = new UPnP(sinkfact.CreatePackage()); UPnP source = new UPnP(sourceFact.CreatePackage()); IPlayqueueHandler pqhandl = new PlayqueueHandler(); PlaybackControl PlayCtrl = new PlaybackControl(sink, pqhandl); DBHandle dbHandle = new DBHandle(source, pqhandl); AbstractFileSenderServer Fserver = new FileSenderServer.FileSenderServer(); Console.WriteLine ("=============================================================="); Console.WriteLine ("Welcome to the HiPi Server solution"); Console.WriteLine ("All UPnP devices SHOULD work, but that's probably not the case"); Console.WriteLine ("Feel free to get our Windows application to get all features"); Console.WriteLine ("Enjoy! ;)"); Console.WriteLine ("=============================================================="); Console.Read(); }
public void Initialize() { if (IsInitialized()) { return; } serverInstance = this; if (server != null) { Debug.LogError("Trying to initial NetServer when it has already been initialized."); return; } if (hostAddress == "" || hostAddress == "Any") { //If no ip given, use 0.0.0.0 hostAddress = IPAddress.Any.ToString(); } if (hostPort == 0) { hostPort = 24424; } if (UnityPacketHandler.instance == null) { GameObject uPH = new GameObject("Unity Packet Handler"); uPH.AddComponent <UnityPacketHandler>(); GameObject.DontDestroyOnLoad(uPH); } if (useSteamworks && !NetTools.isSingleplayer && SteamInteraction.instance == null) { GameObject steamIntegration = new GameObject("Steam Integration Handler"); steamIntegration.AddComponent <SteamInteraction>(); steamIntegration.GetComponent <SteamInteraction>().Initialize(); //steamIntegration.GetComponent<SteamInteraction>().StartServer(); mySteamID = SteamClient.SteamId.Value; GameObject.DontDestroyOnLoad(steamIntegration); } if (NetworkData.instance == null) { Debug.LogWarning("NetworkData object not found."); } UPnP.Init(); //if (packetSendHandler == null) //{ // packetSendHandler = new Thread(new ThreadStart(PacketSendHandler)); // packetSendHandler.Start(); //} if (maxConnections <= 1) { NetTools.isSingleplayer = true; } }
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { ListenServer.Disconnect(); UPnP.DeletePortMap(Ayarlar.ListenPort); notifyIcon.Visible = false; notifyIcon.Dispose(); Instance = null; }
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { ConServer.Disconnect(); UPnP.DeletePortMap(XMLSettings.ListenPort); nIcon.Visible = false; nIcon.Dispose(); Instance = null; }
static public void configureNetwork(string externalIp, int port) { // Network configuration UPnP upnp = new UPnP(); IxianHandler.publicPort = port; if (externalIp != "" && IPAddress.TryParse(externalIp, out _)) { IxianHandler.publicIP = externalIp; } else { IxianHandler.publicIP = ""; List <IPAndMask> local_ips = CoreNetworkUtils.GetAllLocalIPAddressesAndMasks(); foreach (IPAndMask local_ip in local_ips) { if (IPv4Subnet.IsPublicIP(local_ip.Address)) { Logging.info(String.Format("Public IP detected: {0}, mask {1}.", local_ip.Address.ToString(), local_ip.SubnetMask.ToString())); IxianHandler.publicIP = local_ip.Address.ToString(); } } if (IxianHandler.publicIP == "") { IPAddress primary_local = CoreNetworkUtils.GetPrimaryIPAddress(); if (primary_local == null) { Logging.warn("Unable to determine primary IP address."); } else { Logging.warn(String.Format("None of the locally configured IP addresses are public. Attempting UPnP...")); Task <IPAddress> public_ip = upnp.GetExternalIPAddress(); if (public_ip.Wait(1000)) { if (public_ip.Result != null) { Logging.info(String.Format("UPNP-determined public IP: {0}. Attempting to configure a port-forwarding rule.", public_ip.Result.ToString())); if (upnp.MapPublicPort(port, primary_local)) { IxianHandler.publicIP = public_ip.Result.ToString(); //upnp.getMappedIP(); Logging.info(string.Format("Network configured. Public IP is: {0}", IxianHandler.publicIP)); } else { Logging.warn("UPnP configuration failed, please set port forwarding for port {0} manually.", port); } } else { Logging.warn("UPnP configuration failed, please set port forwarding for port {0} manually.", port); } } } } } }
private void Run() { log4net.Config.BasicConfigurator.Configure(); Console.Title = "Press 'q' to quit; 'l' to list devices"; Console.WriteLine("Starting..."); using (var upnp = new UPnP()) { upnp.Start(); var cp = new ControlPoint(true); cp.DeviceAdded += new ControlPoint.DeviceAddedDelegate(cp_DeviceAdded); cp.DeviceRemoved += new ControlPoint.DeviceRemovedDelegate(cp_DeviceRemoved); cp.ActionResponse += new ControlPoint.ActionResponseDelegate(cp_ActionResponse); upnp.AddControlPoint(cp); #region handle keyboard for (bool quit = false; !quit; ) { switch (Console.ReadKey(true).KeyChar) { case 'q': quit = true; break; case 'l': { var devs = cp.Devices; Console.WriteLine("Devices (" + devs.Length + "):"); foreach (var d in devs) { Console.WriteLine(" " + d.FriendlyName); } break; } } } #endregion cp.DeviceAdded -= new ControlPoint.DeviceAddedDelegate(cp_DeviceAdded); cp.DeviceRemoved -= new ControlPoint.DeviceRemovedDelegate(cp_DeviceRemoved); upnp.Stop(); } Console.WriteLine("Stopped."); }
private void Run() { log4net.Config.BasicConfigurator.Configure(); Console.Title = "Press 'q' to quit; 'l' to list devices"; Console.WriteLine("Starting..."); using (var upnp = new UPnP()) { upnp.Start(); var cp = new ControlPoint(true); cp.DeviceAdded += new ControlPoint.DeviceAddedDelegate(cp_DeviceAdded); cp.DeviceRemoved += new ControlPoint.DeviceRemovedDelegate(cp_DeviceRemoved); cp.ActionResponse += new ControlPoint.ActionResponseDelegate(cp_ActionResponse); upnp.AddControlPoint(cp); #region handle keyboard for (bool quit = false; !quit;) { switch (Console.ReadKey(true).KeyChar) { case 'q': quit = true; break; case 'l': { var devs = cp.Devices; Console.WriteLine("Devices (" + devs.Length + "):"); foreach (var d in devs) { Console.WriteLine(" " + d.FriendlyName); } break; } } } #endregion cp.DeviceAdded -= new ControlPoint.DeviceAddedDelegate(cp_DeviceAdded); cp.DeviceRemoved -= new ControlPoint.DeviceRemovedDelegate(cp_DeviceRemoved); upnp.Stop(); } Console.WriteLine("Stopped."); }
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { ListenServer.Disconnect(); UPnP.DeletePortMap(Settings.ListenPort); UnregisterMessageHandler(); _clientStatusHandler.Dispose(); notifyIcon.Visible = false; notifyIcon.Dispose(); }
public IStaticPortMapping Add(int lExternalPort, string bstrProtocol, int lInternalPort, string bstrInternalClient, bool bEnabled, string bstrDescription) { UPnP.Open(Enum.Parse <Protocol>(bstrProtocol), (ushort)lExternalPort, (ushort)lInternalPort, bstrDescription); return(new StaticPortMapping ( InternalPort: lInternalPort, Protocol: bstrProtocol, InternalClient: bstrInternalClient )); }
private void frmMain_Load(object sender, EventArgs e) { listenServer = new Server(8192); listenServer.AddTypesToSerializer(typeof(IPacket), new Type[] { typeof(Core.Packets.ServerPackets.InitializeCommand), typeof(Core.Packets.ServerPackets.Disconnect), typeof(Core.Packets.ServerPackets.Reconnect), typeof(Core.Packets.ServerPackets.Uninstall), typeof(Core.Packets.ServerPackets.DownloadAndExecute), typeof(Core.Packets.ServerPackets.UploadAndExecute), typeof(Core.Packets.ServerPackets.Desktop), typeof(Core.Packets.ServerPackets.GetProcesses), typeof(Core.Packets.ServerPackets.KillProcess), typeof(Core.Packets.ServerPackets.StartProcess), typeof(Core.Packets.ServerPackets.Drives), typeof(Core.Packets.ServerPackets.Directory), typeof(Core.Packets.ServerPackets.DownloadFile), typeof(Core.Packets.ServerPackets.MouseClick), typeof(Core.Packets.ServerPackets.GetSystemInfo), typeof(Core.Packets.ServerPackets.VisitWebsite), typeof(Core.Packets.ServerPackets.ShowMessageBox), typeof(Core.Packets.ServerPackets.Update), typeof(Core.Packets.ServerPackets.Monitors), typeof(Core.Packets.ServerPackets.ShellCommand), typeof(Core.Packets.ServerPackets.Rename), typeof(Core.Packets.ServerPackets.Delete), typeof(Core.Packets.ServerPackets.Action), typeof(Core.Packets.ClientPackets.Initialize), typeof(Core.Packets.ClientPackets.Status), typeof(Core.Packets.ClientPackets.UserStatus), typeof(Core.Packets.ClientPackets.DesktopResponse), typeof(Core.Packets.ClientPackets.GetProcessesResponse), typeof(Core.Packets.ClientPackets.DrivesResponse), typeof(Core.Packets.ClientPackets.DirectoryResponse), typeof(Core.Packets.ClientPackets.DownloadFileResponse), typeof(Core.Packets.ClientPackets.GetSystemInfoResponse), typeof(Core.Packets.ClientPackets.MonitorsResponse), typeof(Core.Packets.ClientPackets.ShellCommandResponse) }); listenServer.ServerState += serverState; listenServer.ClientState += clientState; listenServer.ClientRead += clientRead; if (XMLSettings.AutoListen) { if (XMLSettings.UseUPnP) { UPnP.ForwardPort(ushort.Parse(XMLSettings.ListenPort.ToString())); } listenServer.Listen(XMLSettings.ListenPort); } }
public void StopServer() { if (server != null) { ConnectionPacket cP = new ConnectionPacket(true, "Server Closed."); Packet p = new Packet(Packet.pType.connectionPacket, Packet.sendType.nonbuffered, ENSSerialization.SerializeConnectionPacket(cP)); foreach (NetworkPlayer client in connections) { SendPacket(client, p); //Server Closed Packet. client.tcpClient.Close(); client.tcpClient.Dispose(); } server.Stop(); server = null; if (useSteamworks && !NetTools.isSingleplayer) { SteamInteraction.instance.ShutdownServer(); } UPnP.Shutdown(); } if (udpListener != null) { udpListener.Stop(); udpListener = null; } if (connectionHandler != null) { connectionHandler.Abort(); connectionHandler = null; } if (udpHandler != null) { udpHandler.Abort(); udpHandler = null; } if (GameObject.FindObjectOfType <UnityPacketHandler>() != null) { GameObject.Destroy(GameObject.FindObjectOfType <UnityPacketHandler>().gameObject); } //NetServer.serverInstance = null; connections = new List <NetworkPlayer>(); connectionsByID = new Dictionary <int, NetworkPlayer>(); bufferedPackets = new Dictionary <string, List <Packet> >(); if (NetServer.serverInstance != null && NetServer.serverInstance.myConnection != null) { NetServer.serverInstance.myConnection = null; } NetTools.isServer = false; NetTools.isSingleplayer = false; }
/// <summary> /// Handles the Unchecked event of the upnpShare control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param> private void UpnpShareUnchecked(object sender, RoutedEventArgs e) { if (!_loaded) { return; } Settings.Set("Enable UPnP AV Media Server", false); UPnP.Stop(); }
private static bool DiscoverNeo() { if (UPnP.Discover()) { Console.WriteLine("You have an UPnP-enabled router and your IP is: " + UPnP.ExternalIp); UPnP.ForwardPort(_neoTcpPort, ProtocolType.Tcp, "NEO Tcp"); return(true); } return(false); }
/// <summary> /// UPnP notification of a port being open. /// </summary> void OnPortOpened(UPnP up, int port, ProtocolType protocol, bool success) { if (success) { Tools.Print("UPnP: " + protocol.ToString().ToUpper() + " port " + port + " was opened successfully."); } else { Tools.Print("UPnP: Unable to open " + protocol.ToString().ToUpper() + " port " + port); } }
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { ConServer.Disconnect(); if (UPnP.IsPortForwarded) { UPnP.RemovePort(); } nIcon.Visible = false; nIcon.Dispose(); Instance = null; }
private void FrmMain_Load(object sender, EventArgs e) { InitializeServer(); if (XMLSettings.AutoListen) { if (XMLSettings.UseUPnP) { UPnP.ForwardPort(ushort.Parse(XMLSettings.ListenPort.ToString())); } ListenServer.Listen(XMLSettings.ListenPort); } }
/// <summary> /// Handles the Checked event of the upnpShare control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param> private void UpnpShareChecked(object sender, RoutedEventArgs e) { if (!_loaded) { return; } Settings.Set("Enable UPnP AV Media Server", true); if (Signature.IsActivated) { UPnP.Start(); } }
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { if (ListenServer.Listening) { ListenServer.Disconnect(); } if (XMLSettings.UseUPnP) { UPnP.RemovePort(ushort.Parse(XMLSettings.ListenPort.ToString())); } nIcon.Visible = false; }
public static async void LanGameOptionsMenuInit(Window window, Game game) { GameOptions = new GameOptionsUtil(window, game, "Lan"); if (game.SkirmishManager.IsHosting) { game.SkirmishManager.Settings.MapName = GameOptions.CurrentMap.Name; } // Clear chat field var textChat = (TextBox)window.Controls.FindControl(TextEntryChatPrefix); textChat.Text = string.Empty; var buttonStart = (Button)window.Controls.FindControl($"LanGameOptionsMenu.wnd:ButtonStart"); //TODO: Use the right language strings buttonStart.Text = game.SkirmishManager.IsHosting ? "Play Game" : "Accept"; //game.SkirmishManager.OnStop += () => //{ // //TODO: somehow make this work // game.Scene2D.WndWindowManager.SetWindow(@"Menus\LanLobbyMenu.wnd"); //}; if (window.Tag == NetworkUtils.OnlineTag && game.SkirmishManager.IsHosting) { var listBoxChat = (ListBox)window.Controls.FindControl(ListboxChatWindowLanGamePrefix); var listBoxItem = new ListBoxDataItem(null, new string[] { "Checking UPnP status..." }, ColorRgbaF.White); listBoxChat.Items = new[] { listBoxItem }; if (UPnP.Status == UPnPStatus.Enabled) { if (await UPnP.ForwardPortsAsync()) { listBoxItem.ColumnData[0] = $"Ports forwarded via UPnP. Your external IP is {UPnP.ExternalIP?.ToString() ?? "unknown."}"; } else { listBoxItem.ColumnData[0] = $"Failed to forward ports via UPnP. Your external IP is {UPnP.ExternalIP?.ToString() ?? "unknown."}"; } } else { listBoxItem.ColumnData[0] = "UPnP is disabled."; } } }
private int server_BrowseDirectChildren(Action action, String object_id, String filter, Int32 starting_index, Int32 requested_count, String sort_criteria, HttpRequestContext context) { Console.WriteLine("BrowseDirectChildren: " + object_id); if (object_id != "0") { return(-1); } var item = new MediaItem(); item.Title = "Item"; item.ObjectID = "1"; item.ParentID = "0"; item.Class = new ObjectClass("object.item.audioItem.musicTrack", ""); var resource = new MediaResource(); resource.ProtoInfo = ProtocolInfo.GetProtocolInfoFromMimeType("audio/mp3", true, context); // get list of ips and make sure the ip the request came from is used for the first resource returned // this ensures that clients which look only at the first resource will be able to reach the item List <String> ips = UPnP.GetIpAddresses(true); String localIP = context.LocalAddress.ip; if (localIP != "0.0.0.0") { ips.Remove(localIP); ips.Insert(0, localIP); } // iterate through all ips and create a resource for each foreach (String ip in ips) { resource.URI = new Uri("http://" + ip + ":" + context.LocalAddress.port + "/test/test.mp3").ToString(); item.AddResource(resource); } var didl = Didl.header + item.ToDidl(filter) + Didl.footer; action.SetArgumentValue("Result", didl); action.SetArgumentValue("NumberReturned", "1"); action.SetArgumentValue("TotalMatches", "1"); // update ID may be wrong here, it should be the one of the container? // TODO: We need to keep track of the overall updateID of the CDS action.SetArgumentValue("UpdateId", "1"); return(0); }
public static string GetExternalIP(int clientIndex, OrderManager orderManager) { var address = orderManager.LobbyInfo.ClientWithIndex(clientIndex).IpAddress; if (clientIndex == orderManager.LocalClient.Index && address == IPAddress.Loopback.ToString()) { var externalIP = UPnP.GetExternalIP(); if (externalIP != null) { address = externalIP.ToString(); } } return(address); }
private void OnStart(ChannelsConfig config) { ListenerTcpPort = config.Tcp?.Port ?? 0; ListenerWsPort = config.WebSocket?.Port ?? 0; MinDesiredConnections = config.MinDesiredConnections; MaxConnections = config.MaxConnections; MaxConnectionsPerAddress = config.MaxConnectionsPerAddress; // schedule time to trigger `OnTimer` event every TimerMillisecondsInterval ms timer = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(0, 5000, Context.Self, new Timer(), ActorRefs.NoSender); if ((ListenerTcpPort > 0 || ListenerWsPort > 0) && localAddresses.All(p => !p.IsIPv4MappedToIPv6 || IsIntranetAddress(p)) && UPnP.Discover()) { try { localAddresses.Add(UPnP.GetExternalIP()); if (ListenerTcpPort > 0) { UPnP.ForwardPort(ListenerTcpPort, ProtocolType.Tcp, "NEO Tcp"); } if (ListenerWsPort > 0) { UPnP.ForwardPort(ListenerWsPort, ProtocolType.Tcp, "NEO WebSocket"); } } catch { } } if (ListenerTcpPort > 0) { tcp_manager.Tell(new Tcp.Bind(Self, config.Tcp, options: new[] { new Inet.SO.ReuseAddress(true) })); } if (ListenerWsPort > 0) { var host = "*"; if (!config.WebSocket.Address.GetAddressBytes().SequenceEqual(IPAddress.Any.GetAddressBytes())) { // Is not for all interfaces host = config.WebSocket.Address.ToString(); } ws_host = new WebHostBuilder().UseKestrel().UseUrls($"http://{host}:{ListenerWsPort}").Configure(app => app.UseWebSockets().Run(ProcessWebSocketAsync)).Build(); ws_host.Start(); } }
internal static void Initialize(Arguments args) { Console.WriteLine("Platform is {0}", Platform.CurrentPlatform); AppDomain.CurrentDomain.AssemblyResolve += FileSystem.ResolveAssembly; Settings = new Settings(Platform.SupportDir + "settings.yaml", args); Log.LogPath = Platform.SupportDir + "Logs" + Path.DirectorySeparatorChar; Log.AddChannel("perf", "perf.log"); Log.AddChannel("debug", "debug.log"); Log.AddChannel("sync", "syncreport.log"); Log.AddChannel("server", "server.log"); Log.AddChannel("sound", "sound.log"); if (Settings.Server.DiscoverNatDevices) { UPnP.TryNatDiscovery(); } else { Settings.Server.NatDeviceAvailable = false; Settings.Server.AllowPortForward = false; } FileSystem.Mount("."); // Needed to access shaders Renderer.Initialize(Game.Settings.Graphics.Mode); Renderer = new Renderer(); Console.WriteLine("Available mods:"); foreach (var mod in Mod.AllMods) { Console.WriteLine("\t{0}: {1} ({2})", mod.Key, mod.Value.Title, mod.Value.Version); } Sound.Create(Settings.Sound.Engine); InitializeWithMods(Settings.Game.Mods); if (Settings.Server.DiscoverNatDevices) { RunAfterDelay(Settings.Server.NatDiscoveryTimeout, () => UPnP.TryStoppingNatDiscovery() ); } }
private void Run() { log4net.Config.BasicConfigurator.Configure(); Console.Title = "Press 'q' to quit"; Console.WriteLine("Starting..."); using (var upnp = new UPnP()) { var server = new MediaServer("TestManaged"); server.BrowseMetadata += new MediaServer.BrowseMetadataDelegate(server_BrowseMetadata); server.BrowseDirectChildren += new MediaServer.BrowseDirectChildrenDelegate(server_BrowseDirectChildren); server.ProcessFileRequest += new MediaServer.ProcessFileRequestDelegate(server_ProcessFileRequest); upnp.AddDeviceHost(server); upnp.Start(); #region handle keyboard for (bool quit = false; !quit; ) { switch (Console.ReadKey(true).KeyChar) { case 'q': quit = true; break; } } #endregion server.BrowseMetadata -= new MediaServer.BrowseMetadataDelegate(server_BrowseMetadata); server.BrowseDirectChildren -= new MediaServer.BrowseDirectChildrenDelegate(server_BrowseDirectChildren); server.ProcessFileRequest -= new MediaServer.ProcessFileRequestDelegate(server_ProcessFileRequest); upnp.Stop(); } Console.WriteLine("Stopped."); }