// Client has sent us a message public async Task SendMessage(string messagePacket) { if (string.IsNullOrEmpty(messagePacket)) { return; } var message = await messageService.NewMessageFromPacket(messagePacket); if (message == null) { return; // If our message creation failed } var messageBlob = JsonConvert.SerializeObject(message); await Clients.Group(ChatHubHelper.GroupFor(messagePacket)).ReceiveMessage(messageBlob); }
// Client has requested all messages for this channel public async Task GetChannelMessages(string channelInfoPacket) { ChannelInfoPacket packet; User currentUser; Channel channel; try { packet = JsonConvert.DeserializeObject <ChannelInfoPacket>(channelInfoPacket); currentUser = await userService.ExistingUser(packet.UserCookie); channel = await channelService.GetChannel(packet.Channel); } catch { return; // Error parsing the packet } if (currentUser == null) { return; } // Send channel messages to the validated user var messages = await channelService.MessagesFor(channel); var channelMessages = JsonConvert.SerializeObject(messages); await Clients.Caller.ReceiveAllMessages(channelMessages); // Add the user to the relevant signalR group await Groups.AddToGroupAsync(Context.ConnectionId, ChatHubHelper.GroupFor(channelInfoPacket)); // Notify group they joined var notification = currentUser.Name + " has joined!"; await Clients.Group(ChatHubHelper.GroupFor(channelInfoPacket)).Notification(notification); }