以下是一个使用AspNet Core SignalR和Redux的示例代码,用于发送和接收数据:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace SignalRWithReduxExample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub("/chatHub");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace SignalRWithReduxExample
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
import { createStore, applyMiddleware } from 'redux';
import { createHubConnection, addHubEventListener } from './signalrActions';
import rootReducer from './reducers';
// 创建Redux store
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
// 配置SignalR连接
store.dispatch(createHubConnection('/chatHub'));
// 添加SignalR事件监听器
store.dispatch(addHubEventListener('ReceiveMessage', (user, message) => {
console.log(`Received message from ${user}: ${message}`);
// 在这里处理接收到的消息
}));
export const sendMessage = (user, message) => {
return (dispatch, getState) => {
const connection = getState().signalr.connection;
if (connection) {
connection.invoke('SendMessage', user, message)
.catch(error => console.error(error));
}
};
};
这个例子展示了如何使用AspNet Core SignalR和Redux来发送和接收数据。你可以根据自己的需求进行修改和扩展。