nextjs-signalr-chat/real-time-app/SignalRApp/Hubs/MessageHub.cs

27 lines
892 B
C#
Raw Permalink Normal View History

2024-05-03 23:52:03 +10:00
using Microsoft.AspNetCore.SignalR;
namespace SignalRApp.Hubs;
public class UserMessage
{
public required string Sender { get; set; }
public required string Content { get; set; }
public DateTime SentTime { get; set; }
}
public class MessagingHub : Hub
{
private static readonly List<UserMessage> MessageHistory = new List<UserMessage>();
public async Task PostMessage(string content)
{
var senderId = Context.ConnectionId;
var userMessage = new UserMessage
{
Sender = senderId,
Content = content,
SentTime = DateTime.UtcNow
};
MessageHistory.Add(userMessage);
await Clients.Others.SendAsync("ReceiveMessage", senderId, content, userMessage.SentTime);
}
public async Task RetrieveMessageHistory() =>
await Clients.Caller.SendAsync("MessageHistory", MessageHistory);
}