├── Chat.Api ├── Adapters │ ├── IConnectionAdapter.cs │ ├── ServerSentEventsAdapter.cs │ ├── WebSocketAdapter.cs │ └── LongPollingAdapter.cs ├── appsettings.Development.json ├── appsettings.json ├── Chat.Api.csproj ├── Properties │ └── launchSettings.json ├── api.http ├── Dockerfile ├── LongPollingUserRepository.cs ├── Messages.cs ├── LongPollingConnectionStatusChecker.cs ├── Program.cs └── MessagingService.cs ├── docker-compose.yml ├── .github └── workflows │ ├── static.yml │ └── server.yml ├── README.md ├── Chat.sln ├── test ├── server-sent-events.js └── long-polling.js ├── web-client ├── index.html ├── styles.css └── app.js └── .gitignore /Chat.Api/Adapters/IConnectionAdapter.cs: -------------------------------------------------------------------------------- 1 | namespace Chat.Api.Adapters; 2 | 3 | public interface IConnectionAdapter 4 | { 5 | Task SendMessage(Message message); 6 | } -------------------------------------------------------------------------------- /Chat.Api/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Chat.Api/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Error", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | services: 3 | chat: 4 | image: kova98k/chat:latest 5 | ports: 6 | - "9001:5001" 7 | restart: always 8 | volumes: 9 | - chat:/data 10 | 11 | volumes: 12 | chat: -------------------------------------------------------------------------------- /Chat.Api/Chat.Api.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | true 8 | 9 | 10 | -------------------------------------------------------------------------------- /Chat.Api/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Chat.Api": { 4 | "commandName": "Project", 5 | "dotnetRunMessages": true, 6 | "applicationUrl": "http://localhost:5000", 7 | "environmentVariables": { 8 | "ASPNETCORE_ENVIRONMENT": "Development" 9 | } 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Chat.Api/api.http: -------------------------------------------------------------------------------- 1 | ### Long Poll 2 | 3 | GET http://localhost:5000/lp?name=User&id=a3f2c4b1-1b1b-4c4c-8d8d-9e9e9e9e9e9e 4 | Content-Type: application/json 5 | 6 | ### Post a message 7 | 8 | POST http://localhost:5000/lp/message 9 | Content-Type: application/json 10 | 11 | { 12 | "Name": "User", 13 | "Content": "Hello World!" 14 | } -------------------------------------------------------------------------------- /Chat.Api/Dockerfile: -------------------------------------------------------------------------------- 1 | # Build 2 | FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build 3 | WORKDIR /app 4 | COPY . . 5 | RUN dotnet restore 6 | RUN dotnet publish -c Release -o out 7 | 8 | # Run 9 | FROM mcr.microsoft.com/dotnet/aspnet:8.0 10 | WORKDIR /app 11 | COPY --from=build /app/out . 12 | ENV ASPNETCORE_URLS=http://*:5001 13 | CMD dotnet Chat.Api.dll -------------------------------------------------------------------------------- /Chat.Api/LongPollingUserRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using Chat.Api.Adapters; 3 | 4 | namespace Chat.Api; 5 | 6 | public class LongPollingUser(LongPollingAdapter connection, DateTimeOffset lastSeen, Guid id) 7 | { 8 | public LongPollingAdapter Connection { get; set; } = connection; 9 | public DateTimeOffset LastSeen { get; set; } = lastSeen; 10 | public Guid Id { get; } = id; 11 | } 12 | 13 | // Singleton repository allowing Transient LongPollingAdapter instances to share state. 14 | public class LongPollingUserRepository() 15 | { 16 | public readonly ConcurrentDictionary Users = new(); 17 | public readonly ConcurrentDictionary> Buffer = new(); 18 | } -------------------------------------------------------------------------------- /.github/workflows/static.yml: -------------------------------------------------------------------------------- 1 | name: Frontend 2 | 3 | on: 4 | push: 5 | branches: ["main"] 6 | paths: 7 | - 'web-client/**' 8 | workflow_dispatch: 9 | 10 | permissions: 11 | contents: read 12 | pages: write 13 | id-token: write 14 | 15 | concurrency: 16 | group: "pages" 17 | cancel-in-progress: false 18 | 19 | jobs: 20 | deploy: 21 | environment: 22 | name: github-pages 23 | url: ${{ steps.deployment.outputs.page_url }} 24 | runs-on: ubuntu-latest 25 | steps: 26 | - name: Checkout 27 | uses: actions/checkout@v4 28 | - name: Setup Pages 29 | uses: actions/configure-pages@v4 30 | - name: Upload artifact 31 | uses: actions/upload-pages-artifact@v3 32 | with: 33 | path: './web-client' 34 | - name: Deploy to GitHub Pages 35 | id: deployment 36 | uses: actions/deploy-pages@v4 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Chat 2 | 3 | A multi-transport chat application. Currently supports WebSockets, Long Polling and Server-Sent Events. 4 | 5 | [](https://github.com/kova98/Chat/actions/workflows/static.yml) 6 | [](https://github.com/kova98/Chat/actions/workflows/server.yml) 7 | 8 | https://chat.rokokovac.com/ 9 | 10 |  11 | 12 | # Features 13 | - Use WebSocket, Long Polling or Server-Sent Events 14 | - Join with name 15 | - Send and receive messages 16 | - Active users list 17 | - Chat history 18 | 19 | ## Stack 20 | **Frontend:** HTML, CSS, JavaScript 21 | **Backend:** .NET 8 22 | **Server:** Nginx 23 | **CI/CD:** GitHub Actions 24 | 25 | No additional libraries used. 26 | -------------------------------------------------------------------------------- /.github/workflows/server.yml: -------------------------------------------------------------------------------- 1 | name: Backend 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | workflow_dispatch: 7 | 8 | jobs: 9 | deploy: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v3 13 | 14 | - name: Build the Docker image 15 | working-directory: Chat.Api 16 | run: docker build . -t kova98k/chat:latest 17 | 18 | - name: Log into Docker Hub 19 | uses: docker/login-action@v2 20 | with: 21 | username: kova98k 22 | password: ${{ secrets.DOCKERHUB_TOKEN }} 23 | 24 | - name: Push the image to Docker Hub 25 | run: docker push kova98k/chat:latest 26 | 27 | - name: Pull the image to VM and start it 28 | uses: appleboy/ssh-action@v1.0.0 29 | with: 30 | host: ${{ secrets.SSH_HOST }} 31 | username: ${{ secrets.SSH_USERNAME }} 32 | key: ${{ secrets.SSH_KEY }} 33 | script: | 34 | cd playground 35 | docker compose pull chat 36 | docker compose up -d chat 37 | -------------------------------------------------------------------------------- /Chat.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Chat.Api", "Chat.Api\Chat.Api.csproj", "{00260902-4E95-4D71-AD26-B4A3FDB30877}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(SolutionProperties) = preSolution 14 | HideSolutionNode = FALSE 15 | EndGlobalSection 16 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 17 | {00260902-4E95-4D71-AD26-B4A3FDB30877}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 18 | {00260902-4E95-4D71-AD26-B4A3FDB30877}.Debug|Any CPU.Build.0 = Debug|Any CPU 19 | {00260902-4E95-4D71-AD26-B4A3FDB30877}.Release|Any CPU.ActiveCfg = Release|Any CPU 20 | {00260902-4E95-4D71-AD26-B4A3FDB30877}.Release|Any CPU.Build.0 = Release|Any CPU 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /Chat.Api/Messages.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace Chat.Api; 4 | 5 | // Required for polymorphic deserialization 6 | [JsonDerivedType(typeof(ChatMessage), typeDiscriminator: "ChatMessage")] 7 | [JsonDerivedType(typeof(UserList), typeDiscriminator: "UserList")] 8 | [JsonDerivedType(typeof(UserConnected), typeDiscriminator: "UserConnected")] 9 | [JsonDerivedType(typeof(UserDisconnected), typeDiscriminator: "UserDisconnected")] 10 | [JsonDerivedType(typeof(History), typeDiscriminator: "History")] 11 | [JsonPolymorphic(UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FailSerialization)] 12 | public record Message(string Type); 13 | 14 | public record ChatMessage(string Name, string Content) : Message(nameof(ChatMessage)); 15 | 16 | public record UserList(IEnumerable Users) : Message(nameof(UserList)); 17 | 18 | public record UserConnected(string Name, string Transport) : Message(nameof(UserConnected)); 19 | 20 | public record UserDisconnected(string Name) : Message(nameof(UserDisconnected)); 21 | 22 | public record History(IEnumerable Messages) : Message(nameof(History)); -------------------------------------------------------------------------------- /test/server-sent-events.js: -------------------------------------------------------------------------------- 1 | // Long Polling load test 2 | 3 | import http from 'k6/http'; 4 | import { sleep } from 'k6'; 5 | 6 | export const options = { 7 | vus: 5000, 8 | duration: '30s', 9 | }; 10 | 11 | export function setup () { 12 | // Initial connection 13 | const rnd = Math.floor(Math.random() * 1000000); 14 | const user = `user${rnd}`; 15 | let lpUrl = `http://localhost:5000/sse?name=${user}`; 16 | const params = { 17 | headers: { 18 | 'Content-Type': 'application/json', 19 | }, 20 | }; 21 | 22 | const response = http.get(lpUrl, params); 23 | 24 | return { user, }; 25 | } 26 | 27 | export default function (data) { 28 | const rnd = Math.floor(Math.random() * 1000000); 29 | const msg = `msg${rnd}`; 30 | const body = JSON.stringify({ 31 | "Name": data.user, 32 | "Content": msg, 33 | }); 34 | const params = { 35 | headers: { 36 | 'Content-Type': 'application/json', 37 | }, 38 | }; 39 | 40 | const msgUrl = `http://localhost:5000/lp/message`; 41 | http.post(msgUrl, body, params); 42 | 43 | sleep(1); 44 | } 45 | -------------------------------------------------------------------------------- /Chat.Api/LongPollingConnectionStatusChecker.cs: -------------------------------------------------------------------------------- 1 | using Chat.Api.Adapters; 2 | 3 | namespace Chat.Api; 4 | 5 | // As we cannot rely on the client to close the connection gracefully, 6 | // We need to do a manual check to see if the user is still connected. 7 | // We consider a lack of long poll for longer than KeepAliveTimerInMiliseconds to be a disconnect. 8 | public class LongPollingConnectionStatusChecker(LongPollingUserRepository repo, MessagingService service, ILogger logger) : BackgroundService 9 | { 10 | private const int KeepAliveTimerInMiliseconds = 5000; 11 | 12 | protected override Task ExecuteAsync(CancellationToken ct) => Task.Run(async () => 13 | { 14 | while (!ct.IsCancellationRequested) 15 | { 16 | foreach (var (name, user) in repo.Users) 17 | { 18 | if (DateTimeOffset.UtcNow - user.LastSeen > TimeSpan.FromMilliseconds(KeepAliveTimerInMiliseconds)) 19 | { 20 | logger.LogWarning("Disconnecting user {name} due to timeout", name); 21 | await service.RemoveUser(name); 22 | await user.Connection.CloseConnection("Timeout"); 23 | } 24 | } 25 | 26 | await Task.Delay(KeepAliveTimerInMiliseconds, ct); 27 | } 28 | }, ct); 29 | } -------------------------------------------------------------------------------- /test/long-polling.js: -------------------------------------------------------------------------------- 1 | // Long Polling load test 2 | 3 | import http from 'k6/http'; 4 | import { sleep } from 'k6'; 5 | 6 | export const options = { 7 | vus: 5000, 8 | duration: '30s', 9 | }; 10 | 11 | export function setup () { 12 | // Initial connection 13 | const rnd = Math.floor(Math.random() * 1000000); 14 | const user = `user${rnd}`; 15 | let lpUrl = `http://localhost:5000/lp?name=${user}`; 16 | const params = { 17 | headers: { 18 | 'Content-Type': 'application/json', 19 | }, 20 | }; 21 | 22 | const response = http.get(lpUrl, params); 23 | const id = response.headers['X-Connection-Id'] 24 | 25 | return { user, lpUrl, id }; 26 | } 27 | 28 | export default function (data) { 29 | const rnd = Math.floor(Math.random() * 1000000); 30 | const msg = `msg${rnd}`; 31 | const body = JSON.stringify({ 32 | "Name": data.user, 33 | "Content": msg, 34 | }); 35 | const params = { 36 | headers: { 37 | 'Content-Type': 'application/json', 38 | }, 39 | }; 40 | 41 | const msgUrl = `http://localhost:5000/lp/message`; 42 | http.post(msgUrl, body, params); 43 | 44 | // Wait for messages 45 | const lpUrl = `http://localhost:5000/lp?name=${data.user}&id=${data.id}`; 46 | const res = http.get(lpUrl, params); 47 | 48 | sleep(1); 49 | } 50 | -------------------------------------------------------------------------------- /Chat.Api/Adapters/ServerSentEventsAdapter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Text.Json; 3 | 4 | namespace Chat.Api.Adapters; 5 | 6 | public class ServerSentEventsAdapter(MessagingService service) : IConnectionAdapter 7 | { 8 | private readonly ConcurrentQueue _buffer = new(); 9 | private CancellationTokenSource _cts; 10 | 11 | public async Task HandleServerSentEventsRequest(HttpContext context, CancellationToken ct, string name) 12 | { 13 | _cts = CancellationTokenSource.CreateLinkedTokenSource(ct); 14 | 15 | var error = await service.TryAddUser(this, name); 16 | if (error != null) 17 | { 18 | context.Response.StatusCode = 400; 19 | await context.Response.WriteAsync(error, ct); 20 | return; 21 | } 22 | 23 | context.Response.Headers.Add("Content-Type", "text/event-stream"); 24 | 25 | while (!_cts.IsCancellationRequested) 26 | { 27 | if (_buffer.TryDequeue(out var message)) 28 | { 29 | await context.Response.WriteAsync($"data: ", ct); 30 | await JsonSerializer.SerializeAsync(context.Response.Body, message, cancellationToken: ct); 31 | await context.Response.WriteAsync($"\n\n", ct); 32 | await context.Response.Body.FlushAsync(ct); 33 | } 34 | } 35 | 36 | await service.RemoveUser(name); 37 | } 38 | 39 | public Task CloseConnection(string reason) 40 | { 41 | _cts.Cancel(); 42 | return Task.CompletedTask; 43 | } 44 | 45 | public Task SendMessage(Message message) 46 | { 47 | _buffer.Enqueue(message); 48 | return Task.CompletedTask; 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /Chat.Api/Program.cs: -------------------------------------------------------------------------------- 1 | using Chat.Api; 2 | using Chat.Api.Adapters; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | builder.Services.AddLogging(); 6 | builder.Services.AddSingleton(); 7 | builder.Services.AddTransient(); 8 | builder.Services.AddTransient(); 9 | builder.Services.AddTransient(); 10 | builder.Services.AddSingleton(); 11 | builder.Services.AddHostedService(); 12 | builder.Services.AddCors(options => 13 | { 14 | options.AddPolicy("AllowAnyOrigin", p => p 15 | .AllowAnyOrigin() 16 | .AllowAnyHeader() 17 | .AllowAnyMethod() 18 | .WithExposedHeaders("X-Connection-Id")); 19 | }); 20 | 21 | var app = builder.Build(); 22 | app.UseCors("AllowAnyOrigin"); 23 | app.UseWebSockets(); 24 | 25 | app.Map("/ws", async (string name, HttpContext context, WebSocketAdapter ws) => 26 | { 27 | if (context.WebSockets.IsWebSocketRequest) 28 | { 29 | await ws.HandleUser(context, name); 30 | } 31 | else 32 | { 33 | context.Response.StatusCode = 400; 34 | await context.Response.WriteAsync("Expected a WebSocket request"); 35 | } 36 | }); 37 | 38 | app.Map("sse", async (HttpContext context, CancellationToken ct, ServerSentEventsAdapter adapter, string name) => 39 | await adapter.HandleServerSentEventsRequest(context, ct, name)); 40 | 41 | app.MapGet("/lp", async (HttpContext context, CancellationToken ct, LongPollingAdapter adapter, string name, string? id) => 42 | await adapter.HandleLongPollingRequest(context, ct, name, id)); 43 | 44 | app.MapPost("lp/message", async (MessagingService service, ChatMessage message) => 45 | { 46 | await service.BroadcastMessage(message); 47 | return Results.Ok(); 48 | }); 49 | 50 | app.Run(); 51 | -------------------------------------------------------------------------------- /web-client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Chat 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | Chat 15 | 16 | 17 | 18 | WebSocket 21 | 22 | 23 | 24 | Long Polling 27 | 28 | Server-Sent Events 31 | 32 | 33 | Join 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | asdf 42 | 43 | 44 | 45 | 46 | 47 | Send 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Chat.Api/Adapters/WebSocketAdapter.cs: -------------------------------------------------------------------------------- 1 | using System.Net.WebSockets; 2 | using System.Text; 3 | using System.Text.Json; 4 | 5 | namespace Chat.Api.Adapters; 6 | 7 | public class WebSocketAdapter(MessagingService messagingService, ILogger logger) : IConnectionAdapter 8 | { 9 | private WebSocket Socket; 10 | 11 | public async Task SendMessage(Message message) 12 | { 13 | var messageString = JsonSerializer.Serialize(message); 14 | var buffer = new ArraySegment(Encoding.UTF8.GetBytes(messageString)); 15 | await Socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); 16 | } 17 | 18 | public async Task CloseConnection(string reason) 19 | { 20 | await Socket.CloseAsync(WebSocketCloseStatus.PolicyViolation, reason, default); 21 | } 22 | 23 | public async Task HandleUser(HttpContext context, string name) 24 | { 25 | Socket = await context.WebSockets.AcceptWebSocketAsync(); 26 | 27 | var addUserError = await messagingService.TryAddUser(this, name); 28 | if (addUserError != null) 29 | { 30 | await Socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, addUserError, default); 31 | return; 32 | } 33 | 34 | try 35 | { 36 | await Receive(Socket, async (messageString) => 37 | { 38 | var message = JsonSerializer.Deserialize(messageString); 39 | if (message == null) 40 | { 41 | var error = $"Invalid message '{messageString}'"; 42 | await Socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, error, default); 43 | await messagingService.RemoveUser(name); 44 | return; 45 | } 46 | 47 | await messagingService.BroadcastMessage(message); 48 | }); 49 | 50 | await messagingService.RemoveUser(name); 51 | } 52 | catch (WebSocketException e) 53 | { 54 | await messagingService.RemoveUser(name); 55 | logger.LogError(e, "WebSocket error"); 56 | } 57 | } 58 | 59 | private async Task Receive(WebSocket socket, Func handleMessage) 60 | { 61 | var buffer = new byte[1024 * 2]; 62 | while (socket.State == WebSocketState.Open) 63 | { 64 | var result = await socket.ReceiveAsync(new ArraySegment(buffer), default); 65 | if (result.EndOfMessage == false) 66 | { 67 | await socket.CloseAsync(WebSocketCloseStatus.MessageTooBig, "Max message size is 2KiB.", default); 68 | return; 69 | } 70 | if (result.MessageType == WebSocketMessageType.Close) 71 | { 72 | await Socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, default); 73 | return; 74 | } 75 | if (result.MessageType != WebSocketMessageType.Text) 76 | { 77 | await Socket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Expected text message", default); 78 | return; 79 | } 80 | var messageString = Encoding.UTF8.GetString(buffer[..result.Count]); 81 | 82 | await handleMessage(messageString); 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /Chat.Api/Adapters/LongPollingAdapter.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Text.Json; 3 | 4 | namespace Chat.Api.Adapters; 5 | 6 | public class LongPollingAdapter(MessagingService service, LongPollingUserRepository repo) : IConnectionAdapter 7 | { 8 | private const int TimeoutInSeconds = 30; 9 | 10 | private string _name; 11 | private CancellationTokenSource _timeoutCts; 12 | 13 | public async Task HandleLongPollingRequest(HttpContext ctx, CancellationToken userCt, string name, string? idString) 14 | { 15 | _ = Guid.TryParse(idString, out var id); 16 | 17 | _name = name; 18 | 19 | _timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken()); 20 | _timeoutCts.CancelAfter(TimeSpan.FromSeconds(TimeoutInSeconds)); 21 | 22 | var userExists = repo.Users.TryGetValue(name, out var existingUser); 23 | if (userExists && existingUser!.Id != id) 24 | { 25 | // New user, same name 26 | ctx.Response.StatusCode = 400; 27 | await ctx.Response.WriteAsync($"Name '{name}' already taken", userCt); 28 | return; 29 | } 30 | 31 | if (!userExists) 32 | { 33 | // Completely new user 34 | id = Guid.NewGuid(); 35 | existingUser = new LongPollingUser(this, DateTimeOffset.UtcNow, id); 36 | repo.Users.TryAdd(name, existingUser); 37 | 38 | var error = await service.TryAddUser(this, name); 39 | if (error != null) 40 | { 41 | ctx.Response.StatusCode = 400; 42 | await ctx.Response.WriteAsync(error, userCt); 43 | return; 44 | } 45 | 46 | } 47 | // Existing user, retry after timeout 48 | 49 | ctx.Response.Headers.Add("X-Connection-Id", id.ToString()); 50 | 51 | while (!_timeoutCts.IsCancellationRequested) 52 | { 53 | existingUser.LastSeen = DateTimeOffset.UtcNow; 54 | 55 | if (userCt.IsCancellationRequested) 56 | { 57 | // User closed the connection (left the page or closed the browser) 58 | await service.RemoveUser(_name); 59 | repo.Users.TryRemove(_name, out _); 60 | return; 61 | } 62 | 63 | if (repo.Buffer.TryGetValue(_name, out var buffer) && buffer.Count > 0 ) 64 | { 65 | ctx.Response.StatusCode = (int)HttpStatusCode.OK; 66 | await JsonSerializer.SerializeAsync(ctx.Response.Body, buffer, cancellationToken: userCt); 67 | buffer.Clear(); 68 | return; 69 | } 70 | 71 | // smaller delay makes server more responsive, but decreases performance 72 | await Task.Delay(50); 73 | } 74 | 75 | ctx.Response.StatusCode = (int)HttpStatusCode.NoContent; 76 | } 77 | 78 | public async Task CloseConnection(string reason) 79 | { 80 | await _timeoutCts.CancelAsync(); 81 | repo.Users.TryRemove(_name, out _); 82 | } 83 | 84 | public Task SendMessage(Message message) 85 | { 86 | repo.Buffer 87 | .GetOrAdd(_name, _ => new List()) 88 | .Add(message); 89 | 90 | return Task.CompletedTask; 91 | } 92 | } -------------------------------------------------------------------------------- /Chat.Api/MessagingService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Text; 3 | using System.Text.Json; 4 | using Chat.Api.Adapters; 5 | 6 | namespace Chat.Api; 7 | 8 | public class MessagingService : IAsyncDisposable 9 | { 10 | private const string HistoryFile = "/data/messages.log"; 11 | private const int HistorySize = 500; 12 | 13 | private readonly ConcurrentDictionary Connections = new(); 14 | private readonly ConcurrentQueue History = new(); 15 | private readonly ILogger _logger; 16 | private readonly FileStream _appendStream; 17 | 18 | 19 | public MessagingService(ILogger logger) 20 | { 21 | _logger = logger; 22 | _appendStream = new FileStream(HistoryFile, FileMode.Append, FileAccess.Write, FileShare.Read); 23 | LoadHistory(); 24 | } 25 | 26 | private void LoadHistory() 27 | { 28 | using var reader = new StreamReader(new FileStream(HistoryFile, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite)); 29 | string? line; 30 | 31 | var lastLines = new List(); 32 | while ((line = reader.ReadLine()) != null) 33 | { 34 | // Get the last HistorySize messages 35 | if (lastLines.Count > HistorySize) break; 36 | lastLines.Add(line); 37 | } 38 | 39 | foreach (var messageLine in lastLines) 40 | { 41 | if (JsonSerializer.Deserialize(messageLine) is Message message) 42 | { 43 | _logger.LogInformation("Loading message: {message}, type {type}", message, message.GetType().Name); 44 | History.Enqueue(message); 45 | } 46 | } 47 | } 48 | 49 | public async Task TryAddUser(IConnectionAdapter connection, string name) 50 | { 51 | if (!TryAddUser(name, connection)) 52 | { 53 | return $"Name '{name}' already taken"; 54 | } 55 | 56 | var userConnected = new UserConnected(name, GetTransport(connection)); 57 | var everyoneElse = Connections.Where(x => x.Key != name).Select(x => x.Value); 58 | await BroadcastMessage(userConnected, everyoneElse); 59 | 60 | await SendMessage(connection, new History(History.TakeLast(100))); 61 | await SendMessage(connection, new UserList(Connections.Keys)); 62 | 63 | return null; 64 | } 65 | 66 | private string GetTransport(IConnectionAdapter conn) => conn switch 67 | { 68 | WebSocketAdapter _ => "WebSocket", 69 | ServerSentEventsAdapter _ => "Server-Sent Events", 70 | LongPollingAdapter _ => "Long Polling", 71 | _ => "Unknown transport" 72 | }; 73 | 74 | private bool TryAddUser(string name, IConnectionAdapter connection) 75 | { 76 | if (Connections.ContainsKey(name)) 77 | { 78 | return false; 79 | } 80 | 81 | Connections.TryAdd(name, connection); 82 | 83 | return true; 84 | } 85 | 86 | public Task RemoveUser(string name) 87 | { 88 | Connections.TryRemove(name, out _); 89 | var msg = new UserDisconnected(name); 90 | return BroadcastMessage(msg); 91 | } 92 | 93 | public Task SendMessage(IConnectionAdapter connection, Message message) 94 | { 95 | _logger.LogInformation("Sending message: {message}", message); 96 | 97 | return connection.SendMessage(message); 98 | } 99 | 100 | public async Task BroadcastMessage(Message message, IEnumerable? receivers = null) 101 | { 102 | _logger.LogInformation("Broadcasting message: {message}", message); 103 | 104 | History.Enqueue(message); 105 | 106 | foreach (var connection in receivers ?? Connections.Values) 107 | { 108 | await connection.SendMessage(message); 109 | } 110 | 111 | // Append message, don't wait for it to finish 112 | _ = AppendMessageToHistory(message); 113 | } 114 | 115 | private async Task AppendMessageToHistory(Message message) 116 | { 117 | var json = JsonSerializer.Serialize(message) + Environment.NewLine; 118 | var bytes = Encoding.UTF8.GetBytes(json); 119 | await _appendStream.WriteAsync(bytes); 120 | await _appendStream.FlushAsync(); // Ensure it's written to disk 121 | } 122 | 123 | public async ValueTask DisposeAsync() 124 | { 125 | if (_appendStream != null) 126 | { 127 | await _appendStream.FlushAsync(); 128 | await _appendStream.DisposeAsync(); 129 | } 130 | } 131 | } -------------------------------------------------------------------------------- /web-client/styles.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --background-color: #2C2C2C; 3 | --primary-color: #3A3A3A; 4 | --accent-color: #FF6700; 5 | --font-color: #E0E0E0; 6 | } 7 | 8 | body { 9 | font-size: 16px; 10 | display: flex; 11 | flex-direction: column; 12 | align-items: center; 13 | justify-content: center; 14 | height: 100vh; 15 | margin: 0; 16 | font-family: Arial, Helvetica, sans-serif; 17 | background-color: var(--background-color); 18 | color: var(--font-color); 19 | } 20 | 21 | .home-container { 22 | display: flex; 23 | flex-direction: column; 24 | align-items: stretch; 25 | justify-content: center; 26 | background-color: var(--primary-color); 27 | border-radius: 8px; 28 | box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); 29 | padding: 20px 50px 50px 50px; 30 | width: 50vw; 31 | max-width: 320px; 32 | } 33 | 34 | .status { 35 | margin-bottom: 12px; 36 | color: var(--font-color); 37 | text-align: center; 38 | text-shadow: 0 0 4px rgba(0, 0, 0, 0.1); 39 | } 40 | 41 | h1 { 42 | text-align: center; 43 | margin-bottom: 16px; 44 | } 45 | 46 | .button, .input { 47 | flex-grow: 1; 48 | width: 100%; 49 | margin: 4px 0; 50 | } 51 | 52 | .button { 53 | padding: 8px 16px; 54 | border: none; 55 | border-radius: 4px; 56 | background-color: var(--accent-color); 57 | color: white; 58 | cursor: pointer; 59 | max-height: 40px; 60 | } 61 | 62 | .button:disabled { 63 | background-color: grey; 64 | cursor: not-allowed; 65 | } 66 | 67 | .button:disabled:hover { 68 | background-color: grey; 69 | } 70 | 71 | .button:hover { 72 | background-color: #E05A00; 73 | } 74 | 75 | .transport-picker { 76 | display: flex; 77 | flex-direction: row; 78 | align-items: center; 79 | justify-content: space-between; 80 | } 81 | 82 | .transport-button { 83 | margin-right: 10px; 84 | background-color: grey; 85 | } 86 | 87 | .transport-button.selected { 88 | font-weight: bold; 89 | background-color: var(--accent-color); 90 | } 91 | 92 | .transport-button:last-child { 93 | margin-right: 0; 94 | } 95 | 96 | .button:disabled { 97 | background-color: grey; 98 | cursor: not-allowed; 99 | } 100 | 101 | .button:disabled:hover { 102 | background-color: grey; 103 | } 104 | 105 | .input { 106 | padding: 8px 16px; 107 | border: 2px solid var(--background-color); 108 | border-radius: 4px; 109 | background-color: var(--background-color); 110 | color: var(--text-color); 111 | font-size: 16px; 112 | box-sizing: border-box; 113 | } 114 | 115 | .input:focus { 116 | border-color: #FF8C00; 117 | outline: none; 118 | } 119 | 120 | .label { 121 | font-size: 16px; 122 | color: #FFFFFF; 123 | margin-bottom: 8px; 124 | display: block; 125 | } 126 | 127 | .chat-container { 128 | display: flex; 129 | flex-direction: row; 130 | align-items: stretch; 131 | justify-content: center; 132 | background-color: var(--primary-color); 133 | border-radius: 8px; 134 | box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); 135 | padding: 50px; 136 | height: 70vh; 137 | width: 50vw; 138 | } 139 | 140 | .chat { 141 | width: 80%; 142 | display: flex; 143 | flex-direction: column; 144 | } 145 | 146 | .users-list { 147 | width: 20%; 148 | margin-left: 16px; 149 | margin-bottom: 4px; 150 | border-left: 2px solid grey; 151 | padding-left: 16px; 152 | } 153 | 154 | .mobile-users-list { 155 | display:none; 156 | } 157 | 158 | .current-user { 159 | font-weight: bold; 160 | } 161 | 162 | #messages { 163 | display: flex; 164 | flex-direction: column; 165 | overflow-y: scroll; 166 | height: 100%; 167 | overflow-wrap: break-word; 168 | } 169 | 170 | .status-message { 171 | color: grey; 172 | } 173 | 174 | .message-name { 175 | font-weight: bold; 176 | color: var(--accent-color); 177 | } 178 | 179 | .input-section { 180 | margin-top: 16px; 181 | } 182 | 183 | #messages::-webkit-scrollbar { 184 | width: 8px; 185 | } 186 | 187 | #messages::-webkit-scrollbar-track { 188 | background-color: var(--primary-color); 189 | } 190 | 191 | #messages::-webkit-scrollbar-thumb { 192 | background-color: var(--accent-color); 193 | border-radius: 4px; 194 | } 195 | 196 | #messages::-webkit-scrollbar-thumb:hover { 197 | width: 12px; 198 | } 199 | 200 | #error-message { 201 | color: red; 202 | } 203 | 204 | @media (max-width: 768px) { 205 | .home-container { 206 | width: 100vw; 207 | } 208 | 209 | .chat { 210 | width: 100%; 211 | } 212 | 213 | .chat-container { 214 | width: 80vw; 215 | height: 90vh; 216 | padding: 30px; 217 | } 218 | 219 | .users-list { 220 | display:none; 221 | } 222 | 223 | .mobile-users-list { 224 | display: grid; 225 | grid-template-columns: 1fr 1fr; /* Creates 3 equal-width columns */ 226 | gap: 4px; /* Optional: adds spacing between grid items */ 227 | margin-bottom: 4px; 228 | border-bottom: 2px solid grey; 229 | padding-bottom: 16px; 230 | } 231 | 232 | .user { 233 | margin-right: 10px; 234 | } 235 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from `dotnet new gitignore` 5 | 6 | # dotenv files 7 | .env 8 | 9 | # User-specific files 10 | *.rsuser 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Mono auto generated files 20 | mono_crash.* 21 | 22 | # Build results 23 | [Dd]ebug/ 24 | [Dd]ebugPublic/ 25 | [Rr]elease/ 26 | [Rr]eleases/ 27 | x64/ 28 | x86/ 29 | [Ww][Ii][Nn]32/ 30 | [Aa][Rr][Mm]/ 31 | [Aa][Rr][Mm]64/ 32 | bld/ 33 | [Bb]in/ 34 | [Oo]bj/ 35 | [Ll]og/ 36 | [Ll]ogs/ 37 | 38 | # Visual Studio 2015/2017 cache/options directory 39 | .vs/ 40 | # Uncomment if you have tasks that create the project's static files in wwwroot 41 | #wwwroot/ 42 | 43 | # Visual Studio 2017 auto generated files 44 | Generated\ Files/ 45 | 46 | # MSTest test Results 47 | [Tt]est[Rr]esult*/ 48 | [Bb]uild[Ll]og.* 49 | 50 | # NUnit 51 | *.VisualState.xml 52 | TestResult.xml 53 | nunit-*.xml 54 | 55 | # Build Results of an ATL Project 56 | [Dd]ebugPS/ 57 | [Rr]eleasePS/ 58 | dlldata.c 59 | 60 | # Benchmark Results 61 | BenchmarkDotNet.Artifacts/ 62 | 63 | # .NET 64 | project.lock.json 65 | project.fragment.lock.json 66 | artifacts/ 67 | 68 | # Tye 69 | .tye/ 70 | 71 | # ASP.NET Scaffolding 72 | ScaffoldingReadMe.txt 73 | 74 | # StyleCop 75 | StyleCopReport.xml 76 | 77 | # Files built by Visual Studio 78 | *_i.c 79 | *_p.c 80 | *_h.h 81 | *.ilk 82 | *.meta 83 | *.obj 84 | *.iobj 85 | *.pch 86 | *.pdb 87 | *.ipdb 88 | *.pgc 89 | *.pgd 90 | *.rsp 91 | *.sbr 92 | *.tlb 93 | *.tli 94 | *.tlh 95 | *.tmp 96 | *.tmp_proj 97 | *_wpftmp.csproj 98 | *.log 99 | *.tlog 100 | *.vspscc 101 | *.vssscc 102 | .builds 103 | *.pidb 104 | *.svclog 105 | *.scc 106 | 107 | # Chutzpah Test files 108 | _Chutzpah* 109 | 110 | # Visual C++ cache files 111 | ipch/ 112 | *.aps 113 | *.ncb 114 | *.opendb 115 | *.opensdf 116 | *.sdf 117 | *.cachefile 118 | *.VC.db 119 | *.VC.VC.opendb 120 | 121 | # Visual Studio profiler 122 | *.psess 123 | *.vsp 124 | *.vspx 125 | *.sap 126 | 127 | # Visual Studio Trace Files 128 | *.e2e 129 | 130 | # TFS 2012 Local Workspace 131 | $tf/ 132 | 133 | # Guidance Automation Toolkit 134 | *.gpState 135 | 136 | # ReSharper is a .NET coding add-in 137 | _ReSharper*/ 138 | *.[Rr]e[Ss]harper 139 | *.DotSettings.user 140 | 141 | # TeamCity is a build add-in 142 | _TeamCity* 143 | 144 | # DotCover is a Code Coverage Tool 145 | *.dotCover 146 | 147 | # AxoCover is a Code Coverage Tool 148 | .axoCover/* 149 | !.axoCover/settings.json 150 | 151 | # Coverlet is a free, cross platform Code Coverage Tool 152 | coverage*.json 153 | coverage*.xml 154 | coverage*.info 155 | 156 | # Visual Studio code coverage results 157 | *.coverage 158 | *.coveragexml 159 | 160 | # NCrunch 161 | _NCrunch_* 162 | .*crunch*.local.xml 163 | nCrunchTemp_* 164 | 165 | # MightyMoose 166 | *.mm.* 167 | AutoTest.Net/ 168 | 169 | # Web workbench (sass) 170 | .sass-cache/ 171 | 172 | # Installshield output folder 173 | [Ee]xpress/ 174 | 175 | # DocProject is a documentation generator add-in 176 | DocProject/buildhelp/ 177 | DocProject/Help/*.HxT 178 | DocProject/Help/*.HxC 179 | DocProject/Help/*.hhc 180 | DocProject/Help/*.hhk 181 | DocProject/Help/*.hhp 182 | DocProject/Help/Html2 183 | DocProject/Help/html 184 | 185 | # Click-Once directory 186 | publish/ 187 | 188 | # Publish Web Output 189 | *.[Pp]ublish.xml 190 | *.azurePubxml 191 | # Note: Comment the next line if you want to checkin your web deploy settings, 192 | # but database connection strings (with potential passwords) will be unencrypted 193 | *.pubxml 194 | *.publishproj 195 | 196 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 197 | # checkin your Azure Web App publish settings, but sensitive information contained 198 | # in these scripts will be unencrypted 199 | PublishScripts/ 200 | 201 | # NuGet Packages 202 | *.nupkg 203 | # NuGet Symbol Packages 204 | *.snupkg 205 | # The packages folder can be ignored because of Package Restore 206 | **/[Pp]ackages/* 207 | # except build/, which is used as an MSBuild target. 208 | !**/[Pp]ackages/build/ 209 | # Uncomment if necessary however generally it will be regenerated when needed 210 | #!**/[Pp]ackages/repositories.config 211 | # NuGet v3's project.json files produces more ignorable files 212 | *.nuget.props 213 | *.nuget.targets 214 | 215 | # Microsoft Azure Build Output 216 | csx/ 217 | *.build.csdef 218 | 219 | # Microsoft Azure Emulator 220 | ecf/ 221 | rcf/ 222 | 223 | # Windows Store app package directories and files 224 | AppPackages/ 225 | BundleArtifacts/ 226 | Package.StoreAssociation.xml 227 | _pkginfo.txt 228 | *.appx 229 | *.appxbundle 230 | *.appxupload 231 | 232 | # Visual Studio cache files 233 | # files ending in .cache can be ignored 234 | *.[Cc]ache 235 | # but keep track of directories ending in .cache 236 | !?*.[Cc]ache/ 237 | 238 | # Others 239 | ClientBin/ 240 | ~$* 241 | *~ 242 | *.dbmdl 243 | *.dbproj.schemaview 244 | *.jfm 245 | *.pfx 246 | *.publishsettings 247 | orleans.codegen.cs 248 | 249 | # Including strong name files can present a security risk 250 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 251 | #*.snk 252 | 253 | # Since there are multiple workflows, uncomment next line to ignore bower_components 254 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 255 | #bower_components/ 256 | 257 | # RIA/Silverlight projects 258 | Generated_Code/ 259 | 260 | # Backup & report files from converting an old project file 261 | # to a newer Visual Studio version. Backup files are not needed, 262 | # because we have git ;-) 263 | _UpgradeReport_Files/ 264 | Backup*/ 265 | UpgradeLog*.XML 266 | UpgradeLog*.htm 267 | ServiceFabricBackup/ 268 | *.rptproj.bak 269 | 270 | # SQL Server files 271 | *.mdf 272 | *.ldf 273 | *.ndf 274 | 275 | # Business Intelligence projects 276 | *.rdl.data 277 | *.bim.layout 278 | *.bim_*.settings 279 | *.rptproj.rsuser 280 | *- [Bb]ackup.rdl 281 | *- [Bb]ackup ([0-9]).rdl 282 | *- [Bb]ackup ([0-9][0-9]).rdl 283 | 284 | # Microsoft Fakes 285 | FakesAssemblies/ 286 | 287 | # GhostDoc plugin setting file 288 | *.GhostDoc.xml 289 | 290 | # Node.js Tools for Visual Studio 291 | .ntvs_analysis.dat 292 | node_modules/ 293 | 294 | # Visual Studio 6 build log 295 | *.plg 296 | 297 | # Visual Studio 6 workspace options file 298 | *.opt 299 | 300 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 301 | *.vbw 302 | 303 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 304 | *.vbp 305 | 306 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 307 | *.dsw 308 | *.dsp 309 | 310 | # Visual Studio 6 technical files 311 | *.ncb 312 | *.aps 313 | 314 | # Visual Studio LightSwitch build output 315 | **/*.HTMLClient/GeneratedArtifacts 316 | **/*.DesktopClient/GeneratedArtifacts 317 | **/*.DesktopClient/ModelManifest.xml 318 | **/*.Server/GeneratedArtifacts 319 | **/*.Server/ModelManifest.xml 320 | _Pvt_Extensions 321 | 322 | # Paket dependency manager 323 | .paket/paket.exe 324 | paket-files/ 325 | 326 | # FAKE - F# Make 327 | .fake/ 328 | 329 | # CodeRush personal settings 330 | .cr/personal 331 | 332 | # Python Tools for Visual Studio (PTVS) 333 | __pycache__/ 334 | *.pyc 335 | 336 | # Cake - Uncomment if you are using it 337 | # tools/** 338 | # !tools/packages.config 339 | 340 | # Tabs Studio 341 | *.tss 342 | 343 | # Telerik's JustMock configuration file 344 | *.jmconfig 345 | 346 | # BizTalk build output 347 | *.btp.cs 348 | *.btm.cs 349 | *.odx.cs 350 | *.xsd.cs 351 | 352 | # OpenCover UI analysis results 353 | OpenCover/ 354 | 355 | # Azure Stream Analytics local run output 356 | ASALocalRun/ 357 | 358 | # MSBuild Binary and Structured Log 359 | *.binlog 360 | 361 | # NVidia Nsight GPU debugger configuration file 362 | *.nvuser 363 | 364 | # MFractors (Xamarin productivity tool) working folder 365 | .mfractor/ 366 | 367 | # Local History for Visual Studio 368 | .localhistory/ 369 | 370 | # Visual Studio History (VSHistory) files 371 | .vshistory/ 372 | 373 | # BeatPulse healthcheck temp database 374 | healthchecksdb 375 | 376 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 377 | MigrationBackup/ 378 | 379 | # Ionide (cross platform F# VS Code tools) working folder 380 | .ionide/ 381 | 382 | # Fody - auto-generated XML schema 383 | FodyWeavers.xsd 384 | 385 | # VS Code files for those working on multiple tools 386 | .vscode/* 387 | !.vscode/settings.json 388 | !.vscode/tasks.json 389 | !.vscode/launch.json 390 | !.vscode/extensions.json 391 | *.code-workspace 392 | 393 | # Local History for Visual Studio Code 394 | .history/ 395 | 396 | # Windows Installer files from build outputs 397 | *.cab 398 | *.msi 399 | *.msix 400 | *.msm 401 | *.msp 402 | 403 | # JetBrains Rider 404 | *.sln.iml 405 | .idea 406 | 407 | ## 408 | ## Visual studio for Mac 409 | ## 410 | 411 | 412 | # globs 413 | Makefile.in 414 | *.userprefs 415 | *.usertasks 416 | config.make 417 | config.status 418 | aclocal.m4 419 | install-sh 420 | autom4te.cache/ 421 | *.tar.gz 422 | tarballs/ 423 | test-results/ 424 | 425 | # Mac bundle stuff 426 | *.dmg 427 | *.app 428 | 429 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 430 | # General 431 | .DS_Store 432 | .AppleDouble 433 | .LSOverride 434 | 435 | # Icon must end with two \r 436 | Icon 437 | 438 | 439 | # Thumbnails 440 | ._* 441 | 442 | # Files that might appear in the root of a volume 443 | .DocumentRevisions-V100 444 | .fseventsd 445 | .Spotlight-V100 446 | .TemporaryItems 447 | .Trashes 448 | .VolumeIcon.icns 449 | .com.apple.timemachine.donotpresent 450 | 451 | # Directories potentially created on remote AFP share 452 | .AppleDB 453 | .AppleDesktop 454 | Network Trash Folder 455 | Temporary Items 456 | .apdisk 457 | 458 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 459 | # Windows thumbnail cache files 460 | Thumbs.db 461 | ehthumbs.db 462 | ehthumbs_vista.db 463 | 464 | # Dump file 465 | *.stackdump 466 | 467 | # Folder config file 468 | [Dd]esktop.ini 469 | 470 | # Recycle Bin used on file shares 471 | $RECYCLE.BIN/ 472 | 473 | # Windows Installer files 474 | *.cab 475 | *.msi 476 | *.msix 477 | *.msm 478 | *.msp 479 | 480 | # Windows shortcuts 481 | *.lnk 482 | 483 | # Vim temporary swap files 484 | *.swp 485 | -------------------------------------------------------------------------------- /web-client/app.js: -------------------------------------------------------------------------------- 1 | let eventSource = null; 2 | let socket = null; 3 | let users = []; 4 | let name = localStorage.getItem("name"); 5 | let history = []; 6 | let transport = localStorage.getItem("transport"); 7 | if (!transport) { 8 | transport = "web-socket"; 9 | } 10 | 11 | function selectTransport(t) { 12 | transport = t; 13 | localStorage.setItem("transport", transport); 14 | document.querySelectorAll(".transport-button").forEach((button) => { 15 | button.classList.toggle("selected", button.dataset.transport === transport); 16 | }); 17 | } 18 | 19 | selectTransport(transport); 20 | 21 | let wsServerAddress = 'wss://playground.rokokovac.com/chat'; 22 | let httpServerAddress = 'https://playground.rokokovac.com/chat'; 23 | // let wsServerAddress = "ws://localhost:5000"; 24 | // let httpServerAddress = "http://localhost:5000"; 25 | 26 | const nameInput = document.getElementById("nameInput"); 27 | nameInput.focus(); 28 | nameInput.value = name; 29 | 30 | nameInput.addEventListener("keypress", function (event) { 31 | if (event.key === "Enter" && !event.shiftKey) { 32 | if (name.length > 16) { 33 | return; 34 | } 35 | event.preventDefault(); 36 | connect(); 37 | } 38 | }); 39 | 40 | const connectButton = document.getElementById("connectButton"); 41 | nameInput.addEventListener("input", function (event) { 42 | setStatus(""); 43 | connectButton.disabled = false; 44 | name = nameInput.value.trim(); 45 | if (name.length > 16) { 46 | setStatus("Name is too long"); 47 | connectButton.disabled = true; 48 | return; 49 | } 50 | }); 51 | 52 | const messageInput = document.getElementById("messageInput"); 53 | messageInput.addEventListener("keypress", function (event) { 54 | const messageText = messageInput.value.trim(); 55 | if (event.key === "Enter" && !event.shiftKey) { 56 | if (messageText.length > 256) { 57 | return; 58 | } 59 | 60 | event.preventDefault(); 61 | sendMessage(); 62 | } 63 | }); 64 | 65 | messageInput.addEventListener("input", function (event) { 66 | const error = document.getElementById("error-message"); 67 | error.hidden = true; 68 | sendButton.disabled = false; 69 | const messageText = messageInput.value.trim(); 70 | if (messageText.length > 256) { 71 | error.innerText = "Message is too long"; 72 | error.hidden = false; 73 | const sendButton = document.getElementById("sendButton"); 74 | sendButton.disabled = true; 75 | return; 76 | } 77 | }); 78 | 79 | let polling = false; 80 | 81 | function connect() { 82 | name = nameInput.value.trim(); 83 | if (!name) { 84 | setStatus("Please enter a name."); 85 | return; 86 | } 87 | 88 | if (name.length > 16) { 89 | setStatus("Name is too long."); 90 | return; 91 | } 92 | 93 | localStorage.setItem("name", name); 94 | 95 | setStatus("Connecting..."); 96 | 97 | switch (transport) { 98 | case "long-polling": 99 | if (!polling) { 100 | polling = true; 101 | connectLongPolling(); 102 | } 103 | break; 104 | case "web-socket": 105 | connectWebSocket(); 106 | break; 107 | case "server-sent-events": 108 | connectServerSentEvents(); 109 | break; 110 | default: 111 | console.error("Unknown transport: " + transport); 112 | } 113 | } 114 | 115 | let connectionId = null; 116 | 117 | async function connectLongPolling() { 118 | const nameParam = encodeURIComponent(name); 119 | const url = `${httpServerAddress}/lp?name=${nameParam}&id=${connectionId}`; 120 | 121 | try { 122 | const response = await fetch(url); 123 | 124 | if (response.status == 204) { 125 | // Timed out. No messages. 126 | } else if (!response.ok) { 127 | // Check if response status is not 2xx 128 | const errorText = await response.text(); 129 | polling = false; 130 | goToIndex(); 131 | setStatus(errorText); 132 | return; 133 | } else { 134 | const responseData = await response.json(); 135 | for (let i = 0; i < responseData.length; i++) { 136 | handleMessage(responseData[i]); 137 | } 138 | polling = false; 139 | goToChat(); 140 | // if (!connected) { 141 | // goToChat(); 142 | // connected = true; 143 | // } 144 | } 145 | 146 | connectionId = response.headers.get("X-Connection-Id"); 147 | connectLongPolling(); 148 | } catch (error) { 149 | console.error("Error:", error); 150 | // Handle network error or other fetch exceptions 151 | polling = false; 152 | goToIndex(); 153 | setStatus("Network error"); 154 | } 155 | } 156 | 157 | function connectWebSocket() { 158 | const nameParam = encodeURIComponent(name); 159 | socket = new WebSocket(wsServerAddress + "/ws?name=" + nameParam); 160 | 161 | socket.onopen = function (event) { 162 | goToChat(); 163 | messageInput.focus(); 164 | }; 165 | 166 | socket.onerror = function (event) { 167 | setStatus("Could not reach server."); 168 | }; 169 | 170 | socket.onmessage = function (event) { 171 | const message = JSON.parse(event.data); 172 | handleMessage(message); 173 | }; 174 | 175 | socket.onclose = function (event) { 176 | goToIndex(); 177 | console.log("WebSocket is closed.", event); 178 | let status = event.reason === "" ? "Connection closed." : event.reason; 179 | setStatus(status); 180 | clearHistory(); 181 | users = []; 182 | updateUsersDisplay(); 183 | }; 184 | } 185 | 186 | function connectServerSentEvents() { 187 | eventSource = new EventSource(httpServerAddress + "/sse?name=" + name); 188 | goToChat(); 189 | messageInput.focus(); 190 | 191 | eventSource.onmessage = function (event) { 192 | const message = JSON.parse(event.data); 193 | handleMessage(message); 194 | }; 195 | 196 | 197 | eventSource.onerror = function (event) { 198 | if (eventSource.readyState === EventSource.CLOSED) { 199 | goToIndex(); 200 | let status = event.reason === "" ? "Connection closed." : event.reason; 201 | setStatus(status); 202 | clearHistory(); 203 | users = []; 204 | updateUsersDisplay(); 205 | } else { 206 | console.error("An error occurred:", event); 207 | } 208 | }; 209 | 210 | eventSource.onclose = function (event) { 211 | 212 | }; 213 | } 214 | 215 | function handleMessage(message) { 216 | switch (message.Type) { 217 | case "ChatMessage": 218 | handleChatMessage(message); 219 | break; 220 | case "UserList": 221 | handleUserList(message); 222 | break; 223 | case "History": 224 | handleHistory(message); 225 | break; 226 | case "UserConnected": 227 | handleUserConnected(message); 228 | break; 229 | case "UserDisconnected": 230 | handleUserDisconnected(message); 231 | break; 232 | default: 233 | console.log("Unknown message type: " + message.Type); 234 | } 235 | } 236 | 237 | function clearHistory() { 238 | const messages = document.getElementById("messages"); 239 | messages.innerHTML = ""; 240 | } 241 | 242 | function handleHistory(message) { 243 | for (let i = 0; i < message.Messages.length; i++) { 244 | switch (message.Messages[i].Type) { 245 | case "ChatMessage": 246 | handleChatMessage(message.Messages[i]); 247 | break; 248 | case "UserConnected": 249 | handleUserConnected(message.Messages[i]); 250 | break; 251 | case "UserDisconnected": 252 | handleUserDisconnected(message.Messages[i]); 253 | break; 254 | default: 255 | console.log("Unknown message type: " + message.Messages[i].Type); 256 | } 257 | } 258 | } 259 | 260 | function handleUserConnected(message) { 261 | users.push(message.Name); 262 | updateUsersDisplay(); 263 | 264 | addMessage(`*${message.Name} connected using ${message.Transport}.`, "status-message"); 265 | } 266 | 267 | function handleUserDisconnected(message) { 268 | const index = users.indexOf(message.Name); 269 | if (index > -1) { 270 | users.splice(index, 1); 271 | } 272 | updateUsersDisplay(); 273 | addMessage("* " + message.Name + " disconnected.", "status-message"); 274 | } 275 | 276 | function handleUserList(message) { 277 | users = message.Users; 278 | updateUsersDisplay(); 279 | } 280 | 281 | function updateUsersDisplay() { 282 | const usersList = document.getElementsByClassName("users"); 283 | for (let i = 0; i < usersList.length; i++) { 284 | usersList[i].innerHTML = ""; 285 | for (let j = 0; j < users.length; j++) { 286 | const userElement = document.createElement("div"); 287 | userElement.className = "user"; 288 | userElement.innerText = users[j]; 289 | if (users[j] === name) { 290 | userElement.classList.add("current-user"); 291 | } 292 | usersList[i].appendChild(userElement); 293 | } 294 | } 295 | } 296 | 297 | function handleChatMessage(messageObject) { 298 | const message = document.createElement("div"); 299 | 300 | const messageName = document.createElement("span"); 301 | messageName.innerText = messageObject.Name + ": "; 302 | messageName.className = "message-name"; 303 | message.appendChild(messageName); 304 | 305 | const messageContent = document.createElement("span"); 306 | messageContent.innerText = messageObject.Content; 307 | messageContent.className = "message-content"; 308 | message.appendChild(messageContent); 309 | 310 | const messages = document.getElementById("messages"); 311 | messages.appendChild(message); 312 | messages.scrollTop = messages.scrollHeight; 313 | } 314 | 315 | function addMessage(text, type) { 316 | const message = document.createElement("div"); 317 | message.innerText = text; 318 | message.className = type || "message"; 319 | 320 | const messages = document.getElementById("messages"); 321 | messages.appendChild(message); 322 | messages.scrollTop = messages.scrollHeight; 323 | } 324 | 325 | function sendMessage() { 326 | const messageInput = document.getElementById("messageInput"); 327 | const messageText = messageInput.value.trim(); 328 | if (name && messageText) { 329 | const message = {Type: "ChatMessage", Name: name, Content: messageText}; 330 | switch (transport) { 331 | case "long-polling": 332 | sendMessageHttp(message); 333 | break; 334 | case "server-sent-events": 335 | sendMessageHttp(message); 336 | break; 337 | case "web-socket": 338 | sendMessageWebSocket(JSON.stringify(message)); 339 | break; 340 | default: 341 | console.log("Unknown transport: " + transport); 342 | } 343 | messageInput.value = ""; 344 | messageInput.focus(); 345 | } 346 | } 347 | 348 | function sendMessageHttp(message) { 349 | fetch(httpServerAddress + "/lp/message", { 350 | method: "POST", 351 | headers: { 352 | "Content-Type": "application/json", 353 | }, 354 | body: JSON.stringify(message), 355 | }) 356 | .then((response) => { 357 | if (!response.ok) { 358 | throw new Error(error); 359 | } 360 | }) 361 | .catch((error) => { 362 | goToIndex(); 363 | setStatus(error); 364 | console.error("Error:", error); 365 | }); 366 | } 367 | 368 | function sendMessageWebSocket(message) { 369 | socket.send(message); 370 | } 371 | 372 | function setStatus(statusText) { 373 | const status = currentPage().querySelector(".status"); 374 | status.innerText = statusText; 375 | status.hidden = false; 376 | } 377 | 378 | function goToIndex() { 379 | document.getElementById("homePage").style.display = "block"; 380 | document.getElementById("chatPage").style.display = "none"; 381 | } 382 | 383 | function goToChat() { 384 | document.getElementById("homePage").style.display = "none"; 385 | document.getElementById("chatPage").style.display = "block"; 386 | } 387 | 388 | function currentPage() { 389 | return document.querySelector('.page[style*="display: block"]'); 390 | } 391 | --------------------------------------------------------------------------------