.net Core SignalR 实现
程序员文章站
2023-12-28 15:30:22
...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalRChat
{
public interface IMyClient
{
Task SayAsync(Message message);
}
public class Message
{
public string Titel { get; set; }
public string Content { get; set; }
}
}
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalRChat
{
public class ChatHub : Hub<IMyClient>
{
public async Task SendMessage(string user, string message)
{
//await Clients.All.SendAsync("ReceiveMessage", user, message);
await Clients.Groups<IMyClient>("001house").SayAsync(new Message { Titel = "hello word", Content = "中国_" });
await Clients.All.SayAsync(new Message { Titel = "hello word", Content = "中国" });
}
public override Task OnConnectedAsync()
{
var connectionId = Context.ConnectionId;
Groups.AddToGroupAsync(connectionId, "001house");
return base.OnConnectedAsync();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace SignalRChat
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDistributedRedisCache(options =>
{
options.Configuration = "127.0.0.1:6379,defaultDatabase=1,connectTimeout=1000,connectRetry=1,syncTimeout=10000";
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSignalR().AddRedis("127.0.0.1:6379,defaultDatabase=1,connectTimeout=1000,connectRetry=1,syncTimeout=10000");
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chatHub");
});
app.UseMvc();
}
}
}
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.on("SayAsync", function (message) {
var value = message;
var msg = message.content.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = " says: " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
User..........<input type="text" id="userInput" />
<br />
Message...<input type="text" id="messageInput" />
<input type="button" id="sendButton" value="Send Message" />
</div>
</div>
<div class="row">
<div class="col-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
</div>
<script src="~/lib/signalr/signalr.js"></script>
<script src="~/js/chat.js"></script>
推荐阅读
-
ASP.net core 2.0.0 中 asp.net identity 2.0.0 的基本使用(二)—启用用户管理
-
.Net Core 配置文件的使用
-
.net Core SignalR 实现
-
asp.net core identity学习1
-
.Net core 3.0 SignalR+Vue 实现简单的IM(无jq依赖)
-
ASP.NET Core Identity 实战(4)授权过程
-
ASP.NET Core Identity 实战(3)认证过程
-
.net core 中间件的使用
-
ASP.NET CORE[练习]-Identity-Assertion
-
Asp.net core Identity的配置