singalr 双向通信示例
时间: 2023-09-01 16:09:01 浏览: 34
Sure! Here's an example of bidirectional communication using SignalR in C#:
First, you'll need to set up a SignalR hub class that will handle the communication between the server and the clients:
```csharp
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
// Broadcasts the received message to all connected clients
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
```
Next, configure SignalR in your ASP.NET Core application's `Startup.cs` file:
```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");
});
}
}
```
In your client-side code (e.g., JavaScript), you can establish a connection to the SignalR hub and handle incoming and outgoing messages:
```javascript
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.build();
connection.on("ReceiveMessage", (user, message) => {
// Handle received message
console.log(`${user}: ${message}`);
});
// Send message to the server
connection.invoke("SendMessage", "John", "Hello, SignalR!");
connection.start()
.then(() => {
console.log("SignalR Connected.");
})
.catch(err => {
console.error("SignalR Connection Error: ", err);
});
```
With this setup, when a client sends a message using the `SendMessage` method, the server receives it, and then broadcasts it to all connected clients using the `ReceiveMessage` method. The clients can handle the received message and perform any necessary actions.
Remember to include the SignalR JavaScript library in your client-side code. You can install it via npm or use a CDN.
This is just a basic example to demonstrate bidirectional communication using SignalR. You can extend and customize it according to your specific requirements.