{"id":32492895,"url":"https://github.com/fkucukkara/server-sent-events","last_synced_at":"2026-07-10T13:31:24.849Z","repository":{"id":317993466,"uuid":"1069630846","full_name":"fkucukkara/server-sent-events","owner":"fkucukkara","description":"This project demonstrates how to implement Server-Sent Events (SSE) using the new features introduced in .NET 10.","archived":false,"fork":false,"pushed_at":"2026-05-17T15:01:52.000Z","size":30,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-17T17:29:11.165Z","etag":null,"topics":["csharp","net10","netcore-webapi","server-sent-events","sse"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fkucukkara.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-04T10:09:27.000Z","updated_at":"2026-05-17T15:01:55.000Z","dependencies_parsed_at":"2025-10-08T22:16:36.032Z","dependency_job_id":null,"html_url":"https://github.com/fkucukkara/server-sent-events","commit_stats":null,"previous_names":["fkucukkara/server-sent-events"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/fkucukkara/server-sent-events","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fkucukkara%2Fserver-sent-events","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fkucukkara%2Fserver-sent-events/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fkucukkara%2Fserver-sent-events/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fkucukkara%2Fserver-sent-events/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fkucukkara","download_url":"https://codeload.github.com/fkucukkara/server-sent-events/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fkucukkara%2Fserver-sent-events/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35333326,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-10T02:00:06.465Z","response_time":60,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp","net10","netcore-webapi","server-sent-events","sse"],"created_at":"2025-10-27T11:56:44.891Z","updated_at":"2026-07-10T13:31:24.844Z","avatar_url":"https://github.com/fkucukkara.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Server-Sent Events (SSE) with .NET 10\n\nThis project demonstrates how to implement **Server-Sent Events (SSE)** using the new features introduced in **.NET 10**. It's a simple educational proof-of-concept that shows real-time heart rate monitoring using minimal APIs.\n\n## 🎯 What is Server-Sent Events (SSE)?\n\nServer-Sent Events is a web standard that allows a server to push data to a web page in real-time. Unlike WebSockets, SSE is unidirectional (server-to-client only) and simpler to implement for scenarios where you only need to send data from server to client.\n\n\u003e **Note:** This project uses \"server-sent-events\" (with hyphens) as the standard naming convention for SSE, which is the correct terminology according to the W3C specification.\n\n## 🆕 What's New in .NET 10\n\n.NET 10 introduces native support for Server-Sent Events with:\n\n- **`SseItem\u003cT\u003e`** - Strongly-typed SSE item representation\n- **`TypedResults.ServerSentEvents()`** - Built-in minimal API support\n- **`System.Net.ServerSentEvents`** namespace - Complete SSE framework\n\n## 📁 Project Structure\n\n```\nserver-sent-events/\n├── API/\n│   ├── API.csproj              # .NET 10 project file\n│   ├── Program.cs              # Main application with SSE endpoint\n│   ├── API.http               # HTTP test requests\n│   └── Properties/\n│       └── launchSettings.json # Development settings\n├── global.json                # .NET SDK version pinning\n├── server-sent-events.sln     # Solution file\n└── README.md                  # This file\n```\n\n## 🚀 Features\n\n- ✅ **Pure API** - No UI, just the SSE endpoint\n- ✅ Real-time heart rate simulation (60-100 BPM)\n- ✅ Native .NET 10 SSE implementation\n- ✅ Minimal API with OpenAPI documentation\n- ✅ Proper cancellation token handling\n- ✅ Automatic reconnection support\n- ✅ Type-safe event streaming\n- ✅ Ready for integration with any frontend\n\n## 📋 Prerequisites\n\n- **.NET 10 SDK** - [Download here](https://dotnet.microsoft.com/download/dotnet/10.0)\n- **Visual Studio 2026** or **VS Code** (optional)\n\n## 🛠️ Getting Started\n\n### 1. Clone the Repository\n\n```bash\ngit clone https://github.com/fkucukkara/server-sent-events.git\ncd server-sent-events\n```\n\n### 2. Verify .NET 10 Installation\n\n```bash\ndotnet --version\n# Should show: 10.0.100 or later\n```\n\n### 3. Restore Dependencies\n\n```bash\ndotnet restore\n```\n\n### 4. Build the Project\n\n```bash\ndotnet build\n```\n\n### 5. Run the Application\n\n```bash\ncd API\ndotnet run\n```\n\nThe application will start at `https://localhost:7144`\n\n## 🔌 API Endpoints\n\n| Endpoint | Method | Description | Response Type |\n|----------|--------|-------------|---------------|\n| `/string-item` | GET | SSE stream of heart rate data as plain strings | `text/event-stream` |\n| `/json-item` | GET | SSE stream of heart rate data as JSON objects | `text/event-stream` |\n| `/sse-item` | GET | SSE stream using strongly-typed `SseItem\u003cT\u003e` with reconnection metadata | `text/event-stream` |\n| `/openapi/v1.json` | GET | OpenAPI specification | `application/json` |\n\n## 🧪 Testing the SSE Endpoint\n\n### Option 1: Using VS Code REST Client\n\nOpen `API/API.http` and click \"Send Request\" on the SSE endpoint:\n\n```http\nGET https://localhost:7144/sse-item\nAccept: text/event-stream\nCache-Control: no-cache\n```\n\n### Option 2: Using Browser\n\nNavigate to: `https://localhost:7144/sse-item`\n\nYou'll see a continuous stream of heart rate data:\n\n```\nevent: heartRate\ndata: 75\n\nevent: heartRate\ndata: 82\n\nevent: heartRate\ndata: 68\n```\n\n### Option 3: Using curl\n\n```bash\ncurl -N -H \"Accept: text/event-stream\" https://localhost:7144/sse-item\n```\n\n### Option 4: Using JavaScript Client\n\nCreate your own HTML file to test the SSE endpoint:\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003ctitle\u003eHeart Rate Monitor\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003ch1\u003eReal-time Heart Rate\u003c/h1\u003e\n    \u003cdiv id=\"heartRate\"\u003eConnecting...\u003c/div\u003e\n\n    \u003cscript\u003e\n        const eventSource = new EventSource('https://localhost:7144/sse-item');\n        \n        eventSource.addEventListener('heartRate', function(event) {\n            document.getElementById('heartRate').innerHTML = \n                `❤️ Heart Rate: ${event.data} BPM`;\n        });\n\n        eventSource.onerror = function(event) {\n            console.error('SSE error:', event);\n        };\n    \u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n## 📝 Code Explanation\n\n### Pattern 1 — Plain String Events\n\n```csharp\napp.MapGet(\"/string-item\", (CancellationToken cancellationToken) =\u003e\n{\n    async IAsyncEnumerable\u003cstring\u003e GetHeartRate(\n        [EnumeratorCancellation] CancellationToken cancellationToken)\n    {\n        while (!cancellationToken.IsCancellationRequested)\n        {\n            var heartRate = Random.Shared.Next(60, 100);\n            yield return $\"Heart Rate: {heartRate} bpm\";\n            await Task.Delay(2000, cancellationToken);\n        }\n    }\n\n    return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken), eventType: \"heartRate\");\n});\n```\n\n### Pattern 2 — JSON Object Events\n\n```csharp\napp.MapGet(\"/json-item\", (CancellationToken cancellationToken) =\u003e\n{\n    async IAsyncEnumerable\u003cHeartRateRecord\u003e GetHeartRate(\n        [EnumeratorCancellation] CancellationToken cancellationToken)\n    {\n        while (!cancellationToken.IsCancellationRequested)\n        {\n            var heartRate = Random.Shared.Next(60, 100);\n            yield return HeartRateRecord.Create(heartRate);\n            await Task.Delay(2000, cancellationToken);\n        }\n    }\n\n    return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken), eventType: \"heartRate\");\n});\n\nrecord HeartRateRecord(int HeartRate, DateTime Timestamp)\n{\n    public static HeartRateRecord Create(int heartRate) =\u003e new(heartRate, DateTime.UtcNow);\n}\n```\n\n### Pattern 3 — Strongly-Typed `SseItem\u003cT\u003e` with Metadata\n\n```csharp\napp.MapGet(\"/sse-item\", (CancellationToken cancellationToken) =\u003e\n{\n    async IAsyncEnumerable\u003cSseItem\u003cint\u003e\u003e GetHeartRate(\n        [EnumeratorCancellation] CancellationToken cancellationToken)\n    {\n        while (!cancellationToken.IsCancellationRequested)\n        {\n            var heartRate = Random.Shared.Next(60, 100);\n            yield return new SseItem\u003cint\u003e(heartRate, eventType: \"heartRate\")\n            {\n                ReconnectionInterval = TimeSpan.FromMinutes(1)\n            };\n            await Task.Delay(2000, cancellationToken);\n        }\n    }\n\n    return TypedResults.ServerSentEvents(GetHeartRate(cancellationToken));\n});\n```\n\n### Key Components\n\n1. **`IAsyncEnumerable\u003cT\u003e`** - Async stream of events; `T` can be `string`, a record, or `SseItem\u003cT\u003e`\n2. **`TypedResults.ServerSentEvents()`** - Converts the stream to an SSE (`text/event-stream`) response\n3. **`[EnumeratorCancellation]`** - Proper cancellation token propagation through async enumerables\n4. **`eventType`** - Custom event type for client-side filtering via `addEventListener('heartRate', handler)`\n5. **`ReconnectionInterval`** - Instructs the client how long to wait before reconnecting (only on `SseItem\u003cT\u003e`)\n\n## ⚙️ Configuration\n\n### global.json\n\nEnsures the project uses .NET 10 SDK:\n\n```json\n{\n  \"sdk\": {\n    \"version\": \"10.0.300\",\n    \"rollForward\": \"latestPatch\"\n  }\n}\n```\n\n### Project File (API.csproj)\n\n```xml\n\u003cProject Sdk=\"Microsoft.NET.Sdk.Web\"\u003e\n  \u003cPropertyGroup\u003e\n    \u003cTargetFramework\u003enet10.0\u003c/TargetFramework\u003e\n    \u003cNullable\u003eenable\u003c/Nullable\u003e\n    \u003cImplicitUsings\u003eenable\u003c/ImplicitUsings\u003e\n  \u003c/PropertyGroup\u003e\n\n  \u003cItemGroup\u003e\n    \u003cPackageReference Include=\"Microsoft.AspNetCore.OpenApi\" Version=\"10.0.0\" /\u003e\n  \u003c/ItemGroup\u003e\n\u003c/Project\u003e\n```\n\n## 🌟 SSE vs WebSockets\n\n| Feature | Server-Sent Events | WebSockets |\n|---------|-------------------|------------|\n| **Direction** | Server → Client only | Bidirectional |\n| **Protocol** | HTTP | WebSocket Protocol |\n| **Complexity** | Simple | More complex |\n| **Auto-reconnect** | Built-in | Manual implementation |\n| **Firewall-friendly** | Yes (HTTP) | Sometimes blocked |\n| **Use cases** | Live feeds, notifications | Chat, gaming, collaboration |\n\n## 🎓 Educational Objectives\n\nThis POC demonstrates:\n\n1. **Modern .NET 10 SSE APIs** - Latest framework features\n2. **Minimal APIs** - Simplified web API development\n3. **Async Streaming** - `IAsyncEnumerable` patterns\n4. **Real-time Communication** - Server-to-client data push\n5. **Cancellation Patterns** - Proper resource cleanup\n6. **Type Safety** - Strongly-typed event streaming\n\n## 🚀 Next Steps \u0026 Extensions\n\n### Beginner Extensions\n- Add different event types (temperature, pressure, etc.)\n- Implement event filtering on the client side\n- Add basic error handling and retry logic\n\n### Intermediate Extensions\n- Add authentication and authorization\n- Implement multiple SSE endpoints\n- Add persistent data storage (Entity Framework)\n- Create a web dashboard with charts\n\n### Advanced Extensions\n- Add horizontal scaling with Redis\n- Implement SSE with SignalR fallback\n- Add monitoring and logging\n- Performance testing and optimization\n\n## 📚 Additional Resources\n\n- [Microsoft Docs - SSE in Minimal APIs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/responses?view=aspnetcore-10.0#server-sent-events-sse)\n- [MDN - Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events)\n- [.NET 10 Preview Features](https://devblogs.microsoft.com/dotnet/)\n- [Minimal APIs Documentation](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis)\n\n## License\n[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)\n\nThis project is licensed under the MIT License, which allows you to freely use, modify, and distribute the code. See the [`LICENSE`](LICENSE) file for full details.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffkucukkara%2Fserver-sent-events","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffkucukkara%2Fserver-sent-events","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffkucukkara%2Fserver-sent-events/lists"}