阅读量:5
当用户A发送消息给用户B时,SignalR可以实现实时聊天应用。以下是一个示例:
- 创建一个SignalR Hub类,并在其中定义一个方法接收并转发消息:
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(); } }
- 在前端页面中引用SignalR库,并连接到Hub:
<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>
- 在前端页面中添加发送消息的功能,并调用Hub的方法:
<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的页面上实时显示。