Skip to content

Commit

Permalink
IPC:Auf zufälligem Port lauschen, Besseres Logging,
Browse files Browse the repository at this point in the history
  • Loading branch information
kirides committed May 9, 2019
1 parent d084f4e commit ded6bac
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 13 deletions.
4 changes: 2 additions & 2 deletions Peter/Classes/cDiff.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public static Item[] DiffInt(int[] ArrayA, int[] ArrayB)
return CreateDiffs(DataA, DataB);
} // Diff


static readonly Regex rxWhitespaceToSpace = new Regex("\\s+", RegexOptions.Compiled);
/// <summary>
/// This function converts all textlines of the text into unique numbers for every unique textline
/// so further work can work only with simple numbers.
Expand Down Expand Up @@ -202,7 +202,7 @@ private static int[] DiffCodes(string aText, Hashtable h, bool trimSpace, bool i

if (ignoreSpace)
{
s = Regex.Replace(s, "\\s+", " "); // TODO: optimization: faster blank removal.
s = rxWhitespaceToSpace.Replace(s, " "); // TODO: optimization: faster blank removal.
}

if (ignoreCase)
Expand Down
2 changes: 1 addition & 1 deletion Peter/Forms/MainForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -837,7 +837,7 @@ public void UpdateTitleBar()
}
catch (Exception ex)
{
Log.Line(ex.Message);
Log.Exception(ex);
}
}
}
Expand Down
33 changes: 33 additions & 0 deletions Peter/Http/HttpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -14,6 +15,7 @@ public class HttpServer
{
private readonly HttpListener httpListener = new HttpListener();
private readonly ConcurrentBag<Task> pending = new ConcurrentBag<Task>();
public int Port { get; private set; }

public async Task ListenAsync(string host, HttpRouter router, CancellationToken token)
{
Expand All @@ -37,6 +39,37 @@ public async Task ListenAsync(string host, HttpRouter router, CancellationToken
}
}

public Task ListenLocalAsync(HttpRouter router, CancellationToken token)
{
int port = -1;
for (int i = 0; i < 5; i++)
{
if (TryGetUnusedPort(out port))
{
break;
}
}
if (port == -1)
{
throw new HttpListenerException(0, "Could not find an unused port");
}
return ListenAsync($"http://127.0.0.1:{port}/", router, token);
}

private static bool TryGetUnusedPort(out int port, int startingPort = 49152)
{
var listeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
port = -1;
for (var i = startingPort; i <= 65535; i++)
{
if (listeners.Any(x => x.Port == i)) continue;
port = i;
return true;
}

return false;
}

public void Stop() => httpListener.Stop();
public void Abort() => httpListener.Abort();
}
Expand Down
33 changes: 23 additions & 10 deletions Peter/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ You should have received a copy of the GNU General Public License
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices;
Expand Down Expand Up @@ -58,14 +59,14 @@ private static async Task SwitchToCurrentInstance(string[] args)
files.Add(arg);
}
}
if (files.Count != 0)
if (files.Count != 0 && File.Exists(IpcDat) && int.TryParse(File.ReadLines(IpcDat).First(), out int port))
{
await httpClient.PostAsync($"{listeningAddress}/openfile", new StringContent(string.Join("\n", files), Encoding.Unicode)).ConfigureAwait(false);
await httpClient.PostAsync($"http://127.0.0.1:{port}/openfile", new StringContent(string.Join("\n", files), Encoding.Unicode)).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Log.Line(ex.Message);
Log.Exception(ex);
}
}

Expand All @@ -87,12 +88,12 @@ private static bool IsAlreadyRunning()
}

private static HttpServer httpServer;
private static readonly string listeningAddress = "http://127.0.0.1:32105/";
private static CancellationTokenSource httpServerToken;
private static Task HttpServerListening;

public static readonly string ExePath = Assembly.GetEntryAssembly().Location;
public static readonly string ExeDirectoryPath = Path.GetDirectoryName(ExePath);
private static readonly string IpcDat = Path.Combine(Path.GetTempPath(), "Stampfer.2462342.ipc");
/// <summary>
/// The main entry point for the application.
/// </summary>
Expand All @@ -110,6 +111,7 @@ private static void Main(string[] args)
}
else
{
CleanupTempFiles();
Log.Start();
SetupIPC();
System.Runtime.ProfileOptimization.SetProfileRoot(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));
Expand All @@ -122,7 +124,7 @@ private static void Main(string[] args)
}
catch (Exception ex)
{
Log.Line(ex.Message);
Log.Exception(ex);
}
Log.Flush();
}
Expand All @@ -135,7 +137,8 @@ private static void SetupIPC()
router.HandleRequest("/openfile", HttpOpenFile);
Application.ApplicationExit += ApplicationClosing;
httpServerToken = new CancellationTokenSource();
HttpServerListening = httpServer.ListenAsync(listeningAddress, router, httpServerToken.Token);
HttpServerListening = httpServer.ListenLocalAsync(router, httpServerToken.Token);
File.WriteAllText(IpcDat, httpServer.Port.ToString());
}

private static async Task HttpOpenFile(HttpContext arg)
Expand Down Expand Up @@ -173,20 +176,25 @@ private static async Task HttpOpenFile(HttpContext arg)
}
catch (Exception ex)
{
Log.Line(ex.Message);
Log.Exception(ex);
}
}
private static void CleanupTempFiles()
{
if (File.Exists(IpcDat)) File.Delete(IpcDat);

}
private static void ApplicationClosing(object sender, EventArgs e)
{
try
{
httpServerToken.Cancel();
CleanupTempFiles();
HttpServerListening.GetAwaiter().GetResult();
}
catch (Exception ex)
{
Log.Line(ex.Message);
Log.Exception(ex);
}
}
}
Expand Down Expand Up @@ -241,9 +249,14 @@ public static void Stop()
LogTask = null;
}

public static void Line(string line)
public static void Exception(Exception e)
{
Line($"{e.Source}|{e.Message}", "ERROR");
}

private static void Line(string line, string type)
{
lines.Enqueue(line);
lines.Enqueue($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}|{type}|{line}");
Resume();
}
}
Expand Down

0 comments on commit ded6bac

Please sign in to comment.