-
-
Save ShvedAction/83385d6be12bf0836cf97336678b6547 to your computer and use it in GitHub Desktop.
Example C# HTTP Async Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This isnt async?