Skip to content

Instantly share code, notes, and snippets.

@jelical
Created November 9, 2021 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jelical/b121a75a9c35d63d396d55623e8fcaa8 to your computer and use it in GitHub Desktop.
Save jelical/b121a75a9c35d63d396d55623e8fcaa8 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace jopa
{
public static class Program
{
public static void Main(string[] args)
{
CheckUsage(args);
StartClient(args[1]);
StartServer(args[0]);
}
private static void CheckUsage(string[] args)
{
if (args.Length < 2 || !args.All(a => int.TryParse(a, out _)))
{
Console.WriteLine($"Usage: {Assembly.GetEntryAssembly().GetName().Name} <your port> <his port>");
Environment.Exit(-1);
}
}
private static void StartClient(string port)
{
new Thread(async () =>
{
while (true)
{
using var client = new HttpClient();
var res = Console.ReadLine();
try
{
await client.PostAsync($"http://localhost:{port}", new StringContent(res))
.ConfigureAwait(false);
}
catch
{
Console.WriteLine($"Nobody listening on port {port}");
}
}
}).Start();
}
private static void StartServer(string port)
{
static async Task<string> ReadAll(Stream st)
{
using var reader = new StreamReader(st);
return await reader.ReadToEndAsync();
}
new WebHostBuilder()
.UseSetting(WebHostDefaults.SuppressStatusMessagesKey, "True")
.UseUrls($"http://0.0.0.0:{port}")
.UseKestrel()
.Configure(ab =>
ab.Run(async context => Console.WriteLine(await ReadAll(context.Request.Body))))
.Build()
.Run();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment