當用戶A發送消息給用戶B時,SignalR可以實現實時聊天應用。以下是一個示例:
public class ChatHub : Hub
{
public void SendMessage(string sender, string receiver, string message)
{
Clients.Group(receiver).SendAsync("ReceiveMessage", sender, message);
}
public override Task OnConnectedAsync()
{
Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
return base.OnConnectedAsync();
}
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.3/signalr.min.js"></script>
<script>
var connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.start();
connection.on("ReceiveMessage", function (sender, message) {
// 處理接收到的消息
});
</script>
<input type="text" id="messageInput" />
<button onclick="sendMessage()">Send</button>
<script>
function sendMessage() {
var sender = "UserA";
var receiver = "UserB";
var message = $("#messageInput").val();
connection.invoke("SendMessage", sender, receiver, message);
}
</script>
通過以上示例,用戶A在輸入框中輸入消息并點擊發送按鈕時,消息將通過SignalR實時傳輸到用戶B,并在用戶B的頁面上實時顯示。