Created
October 4, 2017 16:17
-
-
Save amantix/4280808ab28fa1287e834c3ea58561a5 to your computer and use it in GitHub Desktop.
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.Tasks; | |
namespace WebTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var listener = new HttpListener(); | |
listener.Prefixes.Add("http://localhost:8080/"); | |
listener.Start(); | |
Task.Run(async () => | |
{ | |
while (true) | |
{ | |
var ctx = await listener.GetContextAsync(); | |
if(ctx.Request.Headers["Accept"]=="text/event-stream") | |
Task.Factory.StartNew(()=>SSEHandle(ctx)); | |
} | |
}).Wait(); | |
} | |
public static void SSEHandle(HttpListenerContext context) | |
{ | |
var response = context.Response; | |
response.StatusCode = (int)HttpStatusCode.OK; | |
response.ContentType = "text/event-stream"; | |
response.AddHeader("Access-Control-Allow-Origin", "*"); | |
try | |
{ | |
while (true) | |
{ | |
var msg = $"data: {DateTime.Now}\n\n"; | |
var bytes = Encoding.UTF8.GetBytes(msg); | |
response.OutputStream.Write(bytes, 0, bytes.Length); | |
response.OutputStream.Flush(); | |
System.Threading.Thread.Sleep(1000); | |
} | |
} | |
catch (HttpListenerException e) | |
{ | |
Console.WriteLine(e.Message); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment