服务端:

1.引入Microsoft.AspNetCore.SignalR包。

2.新建Hubs文件夹

3.新建XXHub类继承Hub

4.SignalR连接事件

public override Task OnConnectedAsync()
{
  return base.OnConnectedAsync();
}

5.SignalR断开连接事件

public override async Task OnDisconnectedAsync(Exception exception)
{
  await base.OnDisconnectedAsync(exception);
}

6.1获取上下文对象

private readonly IHubContext<YhHub> _hubContext;

public YhHub(IHubContext<YhHub> hubContext)
{
  _hubContext = hubContext;
}

6.2返回客户端消息

返回指定客户端:

await _hubContext.Clients.Client(客户端id).SendAsync(“方法名”, ”返回数据“);

返回所有用户

await _hubContext.Clients.All.SendAsync("方法名","返回数据");

6.3客户端:

引入:<script src="/Scripts/jquery.signalR-3.1.7.js"></script>

连接服务端对应的Hub:

const connection = new signalR.HubConnectionBuilder()
  .withUrl("/SignalR/yh")//yh对应的服务端XXHub
  .configureLogging(signalR.LogLevel.Information)
  .build();

启动:

connection.start()

  .then(function () {

})
.catch(function (error) {
  console.error("连接失败: " + error);
});

// 监听连接关闭事件
connection.onclose(async function () {
  console.log("连接关闭事件");
});

//接收返回数据data

connection.on(”监听服务端方法名“, function (data) {

}

//向服务端方法发送数据

connection.invoke(”服务器方法“,”发送的数据参数“);

7.1配置跨域:在项目Startup.cs 文件的ConfigureServices方法中添加:

services.AddCors(options =>
{
  options.AddPolicy("AllowSpecificOrigin",
  builder =>
  {
    builder.WithOrigins("http://localhost:89", "http://localhost:889")
    .AllowAnyHeader()
    .AllowAnyMethod()
    .AllowCredentials();
  });
});

7.2配置SignalR:在项目Startup.cs 文件的ConfigureServices方法中添加

services.AddSignalR();

7.3在Configure方法中添加:

app.UseCors("AllowSpecificOrigin");

 

7.4配置:

app.UseEndpoints(endpoints =>
{
  endpoints.MapControllers();
  endpoints.MapHub<XXHub>("/yh");
  endpoints.MapGet("/", async context =>
  {
    await context.Response.WriteAsync("Hello World!");
  });
  endpoints.MapControllerRoute(
    name: "webSocket",
    pattern: "websocket",
    defaults: new
    {
      controller = "WebSocket",
      action = "Index"
  });

});

7.5appsettings.json文件: 

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information",
      "Microsoft.AspNetCore.SignalR": "Debug",
      "Microsoft.AspNetCore.Http.Connections": "Debug"
    },
    "Console": {
      "IncludeScopes": true
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "ConnString": "server=(local);uid=用户名;pwd=密码;database=库名;",
    "ConnStringRd": "server=(local);uid=用户名;pwd=密码;database=库名;",
    "ConnStringLog": "server=(local);uid=用户名;pwd=密码;database=库名;"

  }
}

8.SqlSugar配置:

public class DbContext
{
  public DbContext(string connectString)
  {

    Db = new SqlSugarClient(new ConnectionConfig()
    {

      ConnectionString = connectString,
      DbType = DbType.SqlServer,
      InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
      IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了
    });
  }
  public DbContext()
  {

    Db = new SqlSugarClient(new ConnectionConfig()
    {

      ConnectionString = ConfigHelper.GetSectionValue("ConnectionStrings:ConnString"),
      DbType = DbType.SqlServer,
      InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
      IsAutoCloseConnection = true,//开启自动释放模式和EF原理一样我就不多解释了
      SlaveConnectionConfigs = new List<SlaveConnectionConfig>() {//从连接
        new SlaveConnectionConfig() { HitRate=10, ConnectionString=ConfigHelper.GetSectionValue("ConnectionStrings:ConnString") },
        new SlaveConnectionConfig() { HitRate=90, ConnectionString=ConfigHelper.GetSectionValue("ConnectionStrings:ConnStringRd") }
      }
    });

  }
  //注意:不能写成静态的
  public SqlSugarClient Db;//用来处理事务多表查询和复杂的操作

  public SimpleClient<实体类> ApplyDb { get { return new SimpleClient<实体类>(Db); } }//用来处理实体类表的常用操作

}

9.读取配置文件

public class ConfigHelper
{
  public static IConfiguration Configuration;

  static ConfigHelper()
  {
    // 在当前目录或者根目录中寻找appsettings.json文件
    var fileName = "appsettings.json";

    var directory = AppContext.BaseDirectory;
    directory = directory.Replace("\\", "/");

    var filePath = $"{directory}/{fileName}";
    if (!File.Exists(filePath))
    {
      var length = directory.IndexOf("/bin");
      filePath = $"{directory.Substring(0, length)}/{fileName}";
    }

    var builder = new ConfigurationBuilder()
      .AddJsonFile(filePath, false, true);

    Configuration = builder.Build();
  }

  public static string GetSectionValue(string key)
  {
    return Configuration.GetSection(key).Value;
  }
}