11.7.5.5.17 websoket 调用案例
11.7.5.5.17.1 vue组件调用
<el-button label="Pull" @click="onWsPull">Pull</el-button>
<el-button label="Send" @click="onWsSend">Send</el-button>
{{ wsdata }}
11.7.5.5.17.2 method调用方法定义
methods: {
// 监听拉取数据
onWsPull() {
let that = this;
that.$reqWs.pull(
(res) => {
// console.log(res);
that.wsdata.push(JSON.parse(res.result));
},
{
ownerId: "rg",
mkey: "bo-enum-sign",
}
);
},
onWsSend() {
let that = this;
that.$reqWs.send(
JSON.stringify({ name: "发送数据" + that.$verifyGuid.guid() }),
{
ownerId: "rg",
mkey: "bo-enum-sign",
}
);
},
},
11.7.5.5.17.3 req-websoket.js针对平台二次封装
11.7.5.5.17.4 main.js 开启websoket
//打开websoket start
import reqWs from "@/req-websoket";
// "//localhost:58582/ws/api/v3/mkey";
reqWs.url = window.$appConfig.api.root + "/ws/api/v3/mkey";
reqWs.build();
Vue.prototype.$reqWs = reqWs;
//打开websoket end
11.7.5.5.17.5 Startup.cs 接口注入websoket
#region 添加websoket 等消息服务
services.AddSignalR();
//services.AddCors(op =>
//{
// op.AddPolicy("*", set =>
// {
// set.SetIsOriginAllowed(origin => true)
// .AllowAnyHeader()
// .AllowAnyMethod()
// .AllowCredentials();
// });
//});
#endregion
app.UseEndpoints(endpoints =>
{
//endpoints.MapHub<ChatHub>("/ws/api/v3/chat");
//模块数据变更通知
if (_configuration.GetValue<bool>("websoket:open"))
{
endpoints.MapHub<MkeyHub>("/ws/api/v3/mkey");
}
endpoints.MapControllers();
});
11.7.5.5.17.6 MkeyHub接口实现
using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;
namespace RG3.BO.Core.Hubs
{
public class MkeyHub : Hub
{
/**
* 服务端发送消息 模块 数据变更进行通知到前端
*
* owner=ownerId
* mkey=mkey
var result = new
{
lastDate = DateTime.Now,
userId = pf.UserId,
ownerId = pf.OwnerId,
sysId = pf.SysId,
moduleKey = pf.ModuleKey,
reponseField = pf.ReponseField
};
*/
public async Task Send(string owner, string mkey, string json)
{
// Call the broadcastMessage method to update clients.
await Clients.All.SendAsync($"owner-{owner}-mkey-{mkey}", json);
}
}
}
11.7.5.5.17.7 SubPushProvider接口直接推送消息
private readonly DesService _desService;
private readonly IConfiguration _configuration;
private readonly IHubContext<MkeyHub> _hubContext;
private readonly ILogger<SubPushProvider> _logger;
//private readonly IAuthProvider _authProvider;
public SubPushProvider(ILogger<SubPushProvider> logger, IConfiguration configuration, DesService desService, IHubContext<MkeyHub> hubContext)
{
_configuration = configuration;
_desService = desService;
_hubContext = hubContext;
_logger = logger;
// IAuthProvider authProvider,
//_authProvider = authProvider;
}
if (_configuration.GetValue<bool>("websoket:open"))
{
_hubContext.Clients.All.SendAsync($"owner-{pf.OwnerId}-mkey-{pf.ModuleKey}", JsonUtil.Serialize(result));
}
11.7.5.5.17.8 跨域处理
//跨域处理
"withOrigins": "*",
//如果用到websoket, 且需要跨域,需要配置对应的跨域前端地址
"withOriginsValue": [
"http://localhost:5775",
"http://www.localhost:5775",
"http://localhost:5776",
"http://www.localhost:5776",
"http://localhost:5777",
"http://www.localhost:5777",
"http://localhost:5778",
"http://www.localhost:5778"
],
string origins = _configuration.GetValue<string>("withOrigins");
List<string> originsValue = new List<string>();
_configuration.GetSection("withOriginsValue").Bind(originsValue);
app.UseCors(temp =>
{
if (originsValue != null && originsValue.Count > 0)
{
//webSocket 时候使用
temp.WithOrigins(originsValue.ToArray()).SetIsOriginAllowed(origin => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
}
else if (origins == "*")
{
// .AllowCredentials().SetIsOriginAllowed(origin => true).AllowCredentials()
temp.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
}
else
{
//限制运行特定域名跨域访问
temp.WithOrigins(origins.Split(',')).AllowAnyMethod().AllowAnyHeader();
}
});