Last active
June 13, 2019 07:11
-
-
Save cyrilCodePro/496d74994d7bb17d7b55c4ce3c6cf6c9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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