mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-04-26 02:38:54 +02:00
Add WebSockets (#1423)
* Add WebSockets * Add tests * fix * more tests * Add tests * ... * remove IOwin * - * tests * fluent * ok * match * . * byte[] * x * func * func * byte * trans * ... * frameworks......... * jmes * xxx * sc
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net.WebSockets;
|
||||
|
||||
namespace WireMock.WebSockets;
|
||||
|
||||
/// <summary>
|
||||
/// Registry for managing WebSocket connections per mapping
|
||||
/// </summary>
|
||||
internal class WebSocketConnectionRegistry
|
||||
{
|
||||
private readonly ConcurrentDictionary<Guid, WireMockWebSocketContext> _connections = new();
|
||||
|
||||
/// <summary>
|
||||
/// Add a connection to the registry
|
||||
/// </summary>
|
||||
public void AddConnection(WireMockWebSocketContext context)
|
||||
{
|
||||
_connections.TryAdd(context.ConnectionId, context);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove a connection from the registry
|
||||
/// </summary>
|
||||
public void RemoveConnection(Guid connectionId)
|
||||
{
|
||||
_connections.TryRemove(connectionId, out _);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get all connections
|
||||
/// </summary>
|
||||
public IReadOnlyCollection<WireMockWebSocketContext> GetConnections()
|
||||
{
|
||||
return _connections.Values.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Try to get a specific connection
|
||||
/// </summary>
|
||||
public bool TryGetConnection(Guid connectionId, [NotNullWhen(true)] out WireMockWebSocketContext? connection)
|
||||
{
|
||||
return _connections.TryGetValue(connectionId, out connection);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast text to all connections
|
||||
/// </summary>
|
||||
public async Task BroadcastTextAsync(string text, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var tasks = _connections.Values
|
||||
.Where(c => c.WebSocket.State == WebSocketState.Open)
|
||||
.Select(c => c.SendAsync(text, cancellationToken));
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user