服务端不停发送当前时间。
服务端代码:
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
namespace SSEserver
{
class Program
{
static void Main(string[] args)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("Server is running...");
while (true)
{
HttpListenerContext context = listener.GetContext();
ThreadPool.QueueUserWorkItem((_) =>
{
SendEvent(context);
});
}
}
static void SendEvent(HttpListenerContext context)
{
try
{
context.Response.ContentType = "text/event-stream";
context.Response.StatusCode = 200;
context.Response.Headers.Add("Cache-Control", "no-cache");
context.Response.Headers.Add("Connection", "keep-alive");
while (true)
{
string message = $"data: {DateTime.Now.ToString("HH:mm:ss")}\n\n";
byte[] bytes = Encoding.UTF8.GetBytes(message);
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
context.Response.OutputStream.Flush();
Thread.Sleep(1000); // 每秒发送一次消息
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
context.Response.Close();
}
}
}
}
客户端不停接收服务端发送的时间。
客户端代码:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace SSEclient
{
class Program
{
static async Task Main(string[] args)
{
string url = "http://localhost:8080/sse_endpoint"; // SSE endpoint URL
using (HttpClient client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Accept", "text/event-stream");
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
using (var responseStream = await response.Content.ReadAsStreamAsync())
using (var reader = new System.IO.StreamReader(responseStream))
{
while (!reader.EndOfStream)
{
string line = await reader.ReadLineAsync();
if (!string.IsNullOrWhiteSpace(line))
{
Console.WriteLine(line);
// Handle the received SSE event here
}
}
}
}
}
}
}
}