singalr 双向通信详细示例
时间: 2024-04-11 07:33:47 浏览: 17
下面是一个更详细的SignalR双向通信示例:
1. 安装SignalR库:
```
npm install @microsoft/signalr
```
2. 创建SignalR Hub:
在后端创建一个名为ChatHub的SignalR Hub,用于处理消息的发送和接收。
```csharp
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
```
3. 配置SignalR服务:
在Startup.cs文件的`ConfigureServices`方法中添加SignalR服务配置。
```csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chatHub");
});
}
}
```
4. 前端连接SignalR Hub:
在前端页面中创建一个SignalR连接,并处理消息的发送和接收。
```javascript
import * as signalR from "@microsoft/signalr";
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.start()
.then(() => {
console.log("Connected to SignalR hub");
})
.catch((error) => {
console.error("Failed to connect to SignalR hub", error);
});
// 发送消息
function sendMessage() {
const user = document.getElementById("userInput").value;
const message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message)
.catch((error) => {
console.error("Failed to send message", error);
});
}
// 接收消息
connection.on("ReceiveMessage", (user, message) => {
const chatMessage = `${user}: ${message}`;
const li = document.createElement("li");
li.textContent = chatMessage;
document.getElementById("messagesList").appendChild(li);
});
```
5. 前端页面:
在HTML文件中添加一个表单用于输入用户名和消息,以及一个列表用于显示聊天消息。
```html
<!DOCTYPE html>
<html>
<head>
<title>SignalR Chat Example</title>
</head>
<body>
<h1>SignalR Chat Example</h1>
<form onsubmit="event.preventDefault(); sendMessage();">
<input type="text" id="userInput" placeholder="User" />
<input type="text" id="messageInput" placeholder="Message" />
<button type="submit">Send</button>
</form>
<ul id="messagesList"></ul>
<script src="index.js"></script>
</body>
</html>
```
通过以上步骤,你可以在前端页面输入用户名和消息,并将消息发送到后端的SignalR Hub。后端的`SendMessage`方法会将接收到的消息广播给所有连接的客户端,前端通过`on`方法接收到消息并将其显示在列表中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)