服务端
来个最简单的hub类
public class ChatHub:Hub
{
public async Task SendMessage(object user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
public override Task OnConnectedAsync()
{
//这里可以自定义操作 具体您可以看下官方文档
return base.OnConnectedAsync();
}
}
Startup类
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR()
.AddMessagePackProtocol();
//ioc容器中注入了一个 IHubContext<ChatHub> 大家都是老手,就不多bb了
services.AddSingleton<ChatHub>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chat");
});
}
客户端
以最简单的Nodejs 为例
装个包先
$ npm install @microsoft/signalr
js入口文件
这种简单的demo就不多bb了 ^^
//其他东西您可以看看npm文档
var signalR = require('@microsoft/signalr')
var connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:5000/chat")
.configureLogging(signalR.LogLevel.Information)
.build();
async function start() {
await connection.start();
connection.on('ReceiveMessage', (user, message) => {
console.log(user, message);
})
for (let i = 0; i < 100; i++) {
await new Promise(resolve => {
setTimeout(async () => {
await connection.invoke('SendMessage', { name: `user${i}` , age: i }, `msg${i}` )
resolve()
}, 500);
})
}
};
connection.onclose(start);
start();