private async ValueTask StartTcpListen() { using (await _asyncLock.LockAsync()) { var listenAddressSet = new HashSet <OmniAddress>(_tcpAcceptOptions.ListenAddresses.ToArray()); var useUpnp = _tcpAcceptOptions.UseUpnp; UpnpClient?upnpClient = null; try { // TcpListenerの追加処理 foreach (var listenAddress in listenAddressSet) { if (!TryGetEndpoint(listenAddress, out var ipAddress, out ushort port, false)) { continue; } var tcpListener = new TcpListener(ipAddress, port); tcpListener.Start(3); _tcpListeners.Add(tcpListener); if (useUpnp) { // "0.0.0.0"以外はUPnPでのポート開放対象外 if (ipAddress == IPAddress.Any) { if (upnpClient == null) { upnpClient = new UpnpClient(); await upnpClient.ConnectAsync(); } await upnpClient.OpenPortAsync(UpnpProtocolType.Tcp, port, port, "Xeus"); } } } } catch (Exception e) { _logger.Error(e); throw e; } finally { if (upnpClient != null) { upnpClient.Dispose(); } } } }
private async ValueTask StopTcpListen() { using (await _asyncLock.LockAsync()) { var useUpnp = _tcpAcceptOptions.UseUpnp; UpnpClient?upnpClient = null; try { foreach (var tcpListener in _tcpListeners) { var ipEndpoint = (IPEndPoint)tcpListener.LocalEndpoint; tcpListener.Stop(); if (useUpnp) { // "0.0.0.0"以外はUPnPでのポート開放対象外 if (ipEndpoint.Address == IPAddress.Any) { if (upnpClient == null) { upnpClient = new UpnpClient(); await upnpClient.ConnectAsync(); } await upnpClient.ClosePortAsync(UpnpProtocolType.Tcp, ipEndpoint.Port); } } } _tcpListeners.Clear(); } catch (Exception e) { _logger.Error(e); throw e; } finally { if (upnpClient != null) { upnpClient.Dispose(); } } } }