当用户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的页面上实时显示。