abp版本: 4.3.0.0
.net core 版本 2.2
1、Mqtt
1.1 添加程序集:M2MqttDotnetCore(差点以为没有.net core 的)
2.2 实现代码:抄了个单例模式,并将服务器断开和消息接收事件委托给外层
public class MqttClientService { private IConfiguration _config; private static volatile MqttClientService _instance = null; private static readonly object LockHelper = new object(); ////// 创建单例模式 /// public static MqttClientService CreateInstance(IConfiguration config) { if (_instance == null) { lock (LockHelper) { if (_instance == null) _instance = new MqttClientService(config); } } return _instance; } ////// 实例化订阅客户端 /// public MqttClient SubscribeClient { get; set; } public Action
2.signalr,继承 AbpHubBase, ISingletonDependency(实现依赖注入的单例模式),这里只是为了做测试,所以代码有点丑
public class MqttHub : AbpHubBase, ISingletonDependency//AbpHubBase { // 使用GetByUserIdOrNull、GetAllClients和IsOnline方法 获取在线用户信息 private readonly IOnlineClientManager _onlineClient; private readonly IConfiguration _config; public MqttHub(IConfiguration config,IOnlineClientManager onlineClient):base() { _config = config; _onlineClient = onlineClient; } static ListuserList = new List (); /// /// 订阅 这个方法名字是自定义的。参数也是自定义的 /// public async Task SubscribeMessage(string Topic) { MqttClientService service = MqttClientService.CreateInstance(_config); service.ReceivedMsg += MqttHelper_ReceivedMsg; service.ClosedCon += MqttHelper_ClosedCon; await Task.Run(() => service.Subscribe(new string[] { Topic })); } ////// 取消订阅 /// /// public void Unsubscribe(string Topic) { MqttClientService service = MqttClientService.CreateInstance(_config); service.ReceivedMsg += MqttHelper_ReceivedMsg; service.ClosedCon += MqttHelper_ClosedCon; service.Unsubscribe(new string[] { Topic }); } ////// 发布 /// /// /// public void PublishMessage(string Topic, string Data) { MqttClientService service = MqttClientService.CreateInstance(_config); service.ReceivedMsg += MqttHelper_ReceivedMsg; service.ClosedCon += MqttHelper_ClosedCon; service.Publish(Topic, Data);//发布 var clientConnectionId = Context.ConnectionId; //这是与我连接的客户端的连接ID(浏览器端) } ////// 添加在线人员 /// public void AddOnlineUser() { //直接从当前登录者信息里面取 var user = userList.FirstOrDefault(x => x.Id == AbpSession.GetUserId()); if (user == null) { //添加在线人员 userList.Add(new MqttUserModel { ConnectionId = Context.ConnectionId, Id = AbpSession.GetUserId(),//随机用户id UserName = AbpSession.GetUserName(), }); } else { user.ConnectionId = Context.ConnectionId; } Clients.All.SendAsync("getMessage",new { msg = "当前登录用户:" + user.UserName + "\r\n" }); var clientConnectionId = Context.ConnectionId; //这是与我连接的客户端的连接ID(浏览器端) Clients.Client(clientConnectionId).SendAsync("getMessage", new { msg = "您好,欢迎登陆!" });//指定接收者 } ////// /// private void MqttHelper_ClosedCon(object sender, EventArgs e) { Clients.All.SendAsync("getMessage", new { msg = "服务器已断开链接\r\n" }); } ////// 接收到服务器端的返回 /// > private void MqttHelper_ReceivedMsg(object sender, MqttMsgPublishEventArgs e) { byte[] b = e.Message; string str = System.Text.Encoding.UTF8.GetString(b); //All表示监听所有连接上来的客户端。 //getMessage是一个动态的方法,名字我们可以随意定的。这里我仅仅是给他取名叫getMessage而已,我们也可以叫Clients.All.ABC(); Clients.All.SendAsync("getMessage", new { msg = str + "\r\n" });//调用所有连接上来的客户端(包括自己)监听的getMessage事件。All是一个dynamic属性,所以可以随意的监听 } public void SendMessage(string message) { Clients.All.SendAsync("getMessage", new { msg = string.Format("User {0}: {1}", AbpSession.UserId, message) }); } ////// /// ///public async override Task OnConnectedAsync() { await base.OnConnectedAsync(); Logger.Debug("A client connected to MyChatHub: " + Context.ConnectionId); } /// /// 重写父类OnDisconnected方法 :OnConnected方法客户端断开连接的时候会调用此方法 /// /// ///public async override Task OnDisconnectedAsync(Exception exception) { await base.OnDisconnectedAsync(exception); Logger.Debug("A client disconnected from MyChatHub: " + Context.ConnectionId); }
3、前端:
订阅测试
@*服务器地址:
*@订阅主题:
发布测试
发布主题:
发布内容
4 JS
var chatHub = null; abp.signalr.startConnection(abp.appPath + 'signalr-mqttHub', function (connection) { chatHub = connection; // Save a reference to the hub connection.on('getMessage', function (message) { // Register for incoming messages $("#TextArea1").text($("#TextArea1").text() + message.msg + ""); //console.log('received message: ' + message); }); }).then(function (connection) { $("#TextArea1").text($("#TextArea1").text() + "连接MyHub成功\r\n"); //abp.log.debug('Connected to mqttHub server!'); abp.event.trigger('mqttHub.connected'); }); abp.event.on('mqttHub.connected', function () { // Register for connect event chatHub.invoke('sendMessage', "Hi everybody, I'm connected to the chat!"); // Send a message to the server }); $("#btnSubscribe").click(function () { chatHub.invoke('subscribeMessage', $("#txtTopic").val()); }); $("#btnSubscribeNo").click(function () { chatHub.invoke('unsubscribe', $("#txtTopic").val()); }); $("#btnPublic").click(function () { chatHub.invoke('publishMessage', $("#txtPublish").val()) });
5.Startup Configure
app.UseSignalR(routes => { routes.MapHub("/signalr"); routes.MapHub ("/signalr-mqttHub"); // Prefix with '/signalr' });
原谅我写得太匆忙,15分钟居然没有写完,只能后面再补细节