Skip to content

Instantly share code, notes, and snippets.

@ShvedAction
Forked from dynajoe/Program.cs
Last active May 25, 2020 09:53
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 ShvedAction/83385d6be12bf0836cf97336678b6547 to your computer and use it in GitHub Desktop.
Save ShvedAction/83385d6be12bf0836cf97336678b6547 to your computer and use it in GitHub Desktop.
Example C# HTTP Async Server
using System;
using System.Net;
using System.Text;
using System.Threading;
namespace ExampleSimpleWebserver
{
class HttpAsyncServer
{
private string[] listenedAddresses;
private bool isWorked;
private HttpListener listener;
public HttpAsyncServer(string[] listenedAddresses)
{
this.listenedAddresses = listenedAddresses;
isWorked = false;
}
private void HandleRequest(HttpListenerContext context)
{
}
private void work()
{
listener = new HttpListener();
foreach (var prefix in listenedAddresses)
listener.Prefixes.Add(prefix);
listener.Start();
while (isWorked)
{
try
{
var context = listener.GetContext();
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
context.Response.ContentLength64 = buffer.Length;
System.IO.Stream output = context.Response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
}
catch (Exception)
{
}
}
stop();
}
public void stop()
{
isWorked = false;
listener.Stop();
}
public void RunServer()
{
if (isWorked)
throw new Exception("server alredy started");
isWorked = true;
Timer t = new Timer((thread) =>
{
work();
});
t.Change(1, Timeout.Infinite);
Thread.Sleep(10);
}
}
class Program
{
static void Main (string[] args)
{
var server = new HttpAsyncServer(new string[] { "http://localhost:3000/" });
server.RunServer();
Thread.Sleep(30000);
server.stop();
}
}
}
@actopozipc
Copy link

This isnt async?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment