C
C#•4mo ago
Alex

Only response web socket

How to create web socket that doesn't accept any messages, but clients can connect to it and listen for updates? If I don't create while loop, the client immediately disconnects.
if (HttpContext.WebSockets.IsWebSocketRequest)
{

using WebSocket ws = await HttpContext.WebSockets.AcceptWebSocketAsync();

string key = _socketManagerService.AddSocket(ws);

await _socketManagerService.SendAsync(key,new WebSocketMessage
{
MessageType = MessageType.ConnectionEvent,
Data = new WebSocketMessageData
{
Topic = "Connection",
Payload = $"Connection established {DateTime.UtcNow}"
}
});

_logger.LogInformation($"New connection: {key} {DateTime.UtcNow}");

while (!HttpContext.RequestAborted.IsCancellationRequested)
{

}

await _socketManagerService.RemoveSocketAsync(key);
}
if (HttpContext.WebSockets.IsWebSocketRequest)
{

using WebSocket ws = await HttpContext.WebSockets.AcceptWebSocketAsync();

string key = _socketManagerService.AddSocket(ws);

await _socketManagerService.SendAsync(key,new WebSocketMessage
{
MessageType = MessageType.ConnectionEvent,
Data = new WebSocketMessageData
{
Topic = "Connection",
Payload = $"Connection established {DateTime.UtcNow}"
}
});

_logger.LogInformation($"New connection: {key} {DateTime.UtcNow}");

while (!HttpContext.RequestAborted.IsCancellationRequested)
{

}

await _socketManagerService.RemoveSocketAsync(key);
}
6 Replies
Unknown User
Unknown User•4mo ago
Message Not Public
Sign In & Join Server To View
Alex
Alex•4mo ago
it will take some time to understand how it work😅
timetocode
timetocode•4mo ago
You can use signalR
boiled goose
boiled goose•4mo ago
and server sent events
Alex
Alex•4mo ago
I don't understand what to do with socketFinishedTcs. I guess AddSocket saves websocket and task to some dictionary, and later I can remove it from dictictionary with some key. But how it prevents from closing connection with a client?
Unknown User
Unknown User•4mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server
More Posts