Skip to content

Instantly share code, notes, and snippets.

@cyrilCodePro
Last active June 13, 2019 07:11
Show Gist options
  • Save cyrilCodePro/496d74994d7bb17d7b55c4ce3c6cf6c9 to your computer and use it in GitHub Desktop.
Save cyrilCodePro/496d74994d7bb17d7b55c4ce3c6cf6c9 to your computer and use it in GitHub Desktop.
public class WebSocketConnectionManager
{
private ConcurrentDictionary<string, WebSocket> _socketConnection= new ConcurrentDictionary<string, WebSocket>();
public void AddSocket(WebSocket socket)
{
string socketId = CreateConnectionId();
while (!_socketConnection.TryAdd(socketId, socket))
{
socketId = CreateConnectionId();
}
}
public async Task RemoveSocket(string id)
{
try
{
WebSocket socket;
_socketConnection.TryRemove(id, out socket);
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
}
catch (Exception)
{
}
}
public WebSocket GetSocketById(string id)
{
return _socketConnection.FirstOrDefault(m => m.Key == id).Value;
}
public ConcurrentDictionary<string, WebSocket> GetAll()
{
return _socketConnection;
}
public string GetSocketId(WebSocket socket)
{
return _socketConnection.FirstOrDefault(m => m.Value == socket).Key;
}
private string CreateConnectionId()
{
return Guid.NewGuid().ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment