react+umi+netcore+signalR BS和客户端设备 简单通讯

微信扫码登录工作用 仅作记录  

 

 

扫码访问服务器地址

 实现扫码服务器地址通讯中断设备解锁 采用signalR 双向异步通知中断

创建控制器

ChatController 注入集线器上下文 IHubContext

public IActionResult Index(string name)
{
name = name ?? "demo1";
HubContext.Clients.All.SendAsync("SendMeg", $" {name}访问了");
return View();

}

 注:这示例里通知所有终端   实现业务可加入终端ID 对点通知

 

 

 

集线器代码

public class ChatHub :Hub
    {
        //存储当前在线用户
        public static List<ClientModels> clientModels = new List<ClientModels>();

        /// <summary>
        /// 自定义上线 通知服务器上线者设备信息
        /// </summary>
        /// <param name="name"></param>
        public void Online(string name)
        {
            if (string.IsNullOrEmpty(name)) { return; }
            name = Uri.EscapeDataString(name);
            string connId = Context.ConnectionId;
            var model = clientModels.SingleOrDefault(q => q.Name == name);
            if (model == null)
            {
                clientModels.Add(new ClientModels() { ConnectionId = connId, Name = name,Createtime=DateTime.Now });
            }
            else
            {
                //更新令牌
                model.ConnectionId = connId;
            }
}

  

另外实现 主动通知设备页面 采用react+umi+antd 页面 附上fetch后台

 

        public IActionResult SendMsg(string name, string msg)
        {
            
            var model = ChatHub.clientModels.SingleOrDefault(q => q.Name == name);
            if (model != null)
            {
                HubContext.Clients.Client(model.ConnectionId).SendAsync("SendMeg", $" {msg}");
                return Json(new { code = 1 });
            }
            else
            {
                return Json(new { code = 2,msg="发送失败!该客户端不在线" });
            }
        }

  

 

 

posted @ 2019-04-15 10:54  摇光Summer  阅读(452)  评论(0编辑  收藏  举报