public override async Task SendData(IAsyncStreamReader <MyMessage> requestStream, IServerStreamWriter <MyMessage> responseStream, ServerCallContext context) { var httpContext = context.GetHttpContext(); _logger.LogInformation($"Connection id: {httpContext.Connection.Id}"); if (!await requestStream.MoveNext()) { return; } var user = requestStream.Current.Name; _logger.LogInformation($"{user} connected"); var subscriber = new SubscribersModel { Subscriber = responseStream, Name = user }; _serverGrpcSubscribers.AddSubscriber(subscriber); do { await _serverGrpcSubscribers.BroadcastMessageAsync(requestStream.Current); } while (await requestStream.MoveNext()); _serverGrpcSubscribers.RemoveSubscriber(subscriber); _logger.LogInformation($"{user} disconnected"); }
public void AddSubscriber(SubscribersModel subscriber) { bool added = Subscribers.TryAdd(subscriber.Name, subscriber); _logger.LogInformation($"New subscriber added: {subscriber.Name}"); if (!added) { _logger.LogInformation($"could not add subscriber: {subscriber.Name}"); } }
public void RemoveSubscriber(SubscribersModel subscriber) { try { Subscribers.TryRemove(subscriber.Name, out SubscribersModel item); _logger.LogInformation($"Force Remove: {item.Name} - no longer works"); } catch (Exception ex) { _logger.LogError(ex, $"Could not remove {subscriber.Name}"); } }
private async Task <SubscribersModel> SendMessageToSubscriber(SubscribersModel subscriber, MyMessage message) { try { _logger.LogInformation($"Broadcasting: {message.Name} - {message.Message}"); await subscriber.Subscriber.WriteAsync(message); return(null); } catch (Exception ex) { _logger.LogError(ex, "Could not send"); return(subscriber); } }