微信小程序与aspnetcore signalr实例

本文不对小程序与signalr做任何介绍,默认读者已经掌握

aspnetcore Signalr文档

小程序文档

写在之前

SignalR没有提供小程序使用的客户端js,所以本人参考signlar.js写了小程序版signalr-client.js 代码开源,地址 https://github.com/liangshiw/SignalRMiniProgram-Client

先上效果图


开始编码

首先需要创建一个aspnetcore的mvc项目,创建完成后我们需要安装signalr的包

  1. Install-Package Microsoft.AspNetCore.SignalR

现在就可以创建hub集线器了,首先定义一个类来描述已在线的用户,它需要头像和姓名

  1. public class OnlineClient
  2. {
  3. public string NickName { get; set; }
  4. public string Avatar { get; set; }
  5. }

接下来我们在连接创建时,把当前用户做为在线用户添加到字典中,向该用户发送加入成功的系统消息。并且同时向其他的用户发送系统消息

  1. public override async Task OnConnectedAsync()
  2. {
  3. var http = Context.GetHttpContext();
  4. var client = new OnlineClient()
  5. {
  6. NickName = http.Request.Query["nickName"],
  7. Avatar = http.Request.Query["avatar"]
  8. };
  9. lock (SyncObj)
  10. {
  11. OnlineClients[Context.ConnectionId] = client;
  12. }
  13. await base.OnConnectedAsync();
  14. await Groups.AddToGroupAsync(Context.ConnectionId, ChatName);
  15. await Clients.GroupExcept(ChatName, new[] { Context.ConnectionId }).SendAsync("system", $"用户{client.NickName}加入了群聊");
  16. await Clients.Client(Context.ConnectionId).SendAsync("system", $"成功加入{ChatName}");
  17. }

同样在用户断开连接时做离线处理

  1. public override async Task OnDisconnectedAsync(Exception exception)
  2. {
  3. await base.OnDisconnectedAsync(exception);
  4. bool isRemoved;
  5. OnlineClient client;
  6. lock (SyncObj)
  7. {
  8. isRemoved = OnlineClients.TryRemove(Context.ConnectionId, out client);
  9. }
  10. await Groups.RemoveFromGroupAsync(Context.ConnectionId, ChatName);
  11. if (isRemoved)
  12. {
  13. await Clients.GroupExcept(ChatName, new[] { Context.ConnectionId }).SendAsync("system", $"用户{client.NickName}退出了群聊");
  14. }
  15. }

下面就只有一个简单的发送消息方法了,首先查看当前用户是否在线并做相应处理,如果在线就把当前用户的消息和头像姓名一起发送给组中的其他客户端

  1. public async Task SendMessage(string msg)
  2. {
  3. var client = OnlineClients.Where(x => x.Key == Context.ConnectionId).Select(x=>x.Value).FirstOrDefault();
  4. if (client == null)
  5. {
  6. await Clients.Client(Context.ConnectionId).SendAsync("system", "您已不在聊天室,请重新加入");
  7. }
  8. else
  9. {
  10. await Clients.GroupExcept(ChatName, new[] { Context.ConnectionId }).SendAsync("receive", new { msg, nickName = client.NickName, avatar = client.Avatar });
  11. }
  12. }

在小程序中,我们需要在页面加载事件中创建与signalr的连接,并且注册system系统消息与receive用户消息两个方法以接收服务端发来的消息

  1. onLoad: function (options) {
  2. this.hubConnect = new Hub.HubConnection();
  3. this.hubConnect.start("https://chat.jingshonline.net/chat", { nickName: app.globalData.userInfo.nickName, avatar: app.globalData.userInfo.avatarUrl });
  4. this.hubConnect.onOpen = res => {
  5. console.log("成功开启连接")
  6. }
  7. this.hubConnect.on("system", res => {
  8. wx.showModal({
  9. title: '系统消息',
  10. content: res,
  11. })
  12. })
  13. this.hubConnect.on("receive", res => {
  14. centendata.push({
  15. content: res.msg,
  16. time: new Date().toLocaleString(),
  17. head_owner: res.avatar,
  18. is_show_right: 0
  19. });
  20. this.setData({
  21. centendata: centendata
  22. })
  23. })
  24. }

同样在页面销毁时应断开与signalr服务器的连接

  1. onUnload: function () {
  2. this.hubConnect.close({ reason: "退出" })
  3. }

发送方法也非常简单,只需要调用sendMessage方法并把用户输入的消息传入就大功告成了,其它就是页面上的处理了

  1. this.hubConnect.send("sendMessage",message);

完整的代码请去github https://github.com/liangshiw/SignalRMiniProgram-Client/tree/master/sample

需要注意的是在打开小程序代码时,请修改project.config.json文件中的appid,如果项目不错的话还请大家加个星,顺便再follow一下本人

微信小程序与AspNetCore SignalR聊天实例的更多相关文章

  1. 微信小程序实现即时通信聊天功能的实例代码

    项目背景:小程序中实现实时聊天功能 一.服务器域名配置 配置流程 配置参考URL:https://developers.weixin.qq.com/miniprogram/dev/api/api-ne ...

  2. 微信小程序 使用环信聊天工具

    当时做微信小程序环信的时候,没有遇到太多的问题,因为找到了一个例子,有兴趣的朋友可以把这个包下载下来看一下,写的超级的号,使用起来也特别简单,appkey需要自己配置,从环信官网https://con ...

  3. 【微信小程序】自定义模态框实例

    原文链接:https://mp.weixin.qq.com/s/23wPVFUGY-lsTiQBtUdhXA 1 概述 由于官方API提供的显示模态弹窗,只能简单地显示文字内容,不能对对话框内容进行自 ...

  4. 基于vs2015 SignalR开发的微信小程序使用websocket实现聊天功能

    一)前言 在微信小程上实现聊天功能,大致有三种方式:1)小程序云开发 2)购买第三方IM服务 3)使用自己的服务器自己开发. 这里重要讲使用自己的服务器自己开发,并且是基于vs的开发. 网上提供的解决 ...

  5. [转]微信小程序之加载更多(分页加载)实例 —— 微信小程序实战系列(2)

    本文转自;http://blog.csdn.net/michael_ouyang/article/details/56846185 loadmore 加载更多(分页加载) 当用户打开一个页面时,假设后 ...

  6. 微信小程序踩坑集合

    1:官方工具:https://mp.weixin.qq.com/debug/w ... tml?t=1476434678461 2:简易教程:https://mp.weixin.qq.com/debu ...

  7. 微信小程序开发学习资料

    作者:初雪链接:https://www.zhihu.com/question/50907897/answer/128494332来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...

  8. 微信小程序学习指南

    作者:初雪链接:https://www.zhihu.com/question/50907897/answer/128494332来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...

  9. 微信小程序导航:官方工具+精品教程+DEMO集合(1月7更新)

    1:官方工具:https://mp.weixin.qq.com/debug/w ... tml?t=14764346784612:简易教程:https://mp.weixin.qq.com/debug ...

随机推荐

  1. MachineLearningOnCoursera

    Week Six F Score \[\begin{aligned} P &= &\dfrac{2}{\dfrac{1}{P}+\dfrac{1}{R}}\\ &= & ...

  2. PBRT笔记(6)——采样和重构

    前言 本文仅作为个人笔记分享,又因为本章涉及多个专业领域而本人皆未接触过,所以难免出错,请各位读者注意. 对于数字图像需要区分image pixels(特定采样处的函数值)和display pixel ...

  3. 使用anaconda创建tensorflow环境后如何在jupyter notebook中使用

    在以下目录中 C:\Users\UserName\AppData\Roaming\jupyter\kernels\python3 打开kernel.json文件,将python.exe文件的路径修改至 ...

  4. KMP性质小结

    跪拜_Blackjack_神犇

  5. spring创建bean的三种方式

    spring创建bean的三种方式: 1通过构造方法创建bean(最常用) 1.1 spring默认会通过无参构造方法来创建bean,如果xml文件是这样配置,则实体类中必须要有无参构造方法,无参构造 ...

  6. tensor内部结构

    内部结构 1.tensor分为头信息区(Tensor)和存储区(Storage): 信息区:tensor的形状(size).步长(stride).数据类型(type),信息区占用内存较少 存储区:数据 ...

  7. python从入门到实践-10章文件和异常(括号问题)

    #!/user/bin/env python# -*- coding:utf-8 -*- # 1.从文件中读取数据with open('pi_digits.txt') as file_object: ...

  8. boot+Xss防攻击的处理方案

    以下是boot+Xss防攻击的(解决处理JSON入参)处理方案,第二个亲测有效 https://www.jianshu.com/p/3e4b00b8ff3ahttps://www.jianshu.co ...

  9. B4 and After: Managing Hierarchy, Partitioning, and Asymmetry for Availability and Scale in Google’s Sofware-Defined WAN

    B4及之后:为谷歌软件定义WAN的可用性和扩展管理层次化.划分和不对称 本文为SIGCOMM 2018会议论文,由谷歌提供. 笔者翻译了该论文.由于时间仓促,且笔者英文能力有限,错误之处在所难免:欢迎 ...

  10. 3-2 Hadoop集群伪分布模式配置部署

    Hadoop伪分布模式配置部署 一.实验介绍 1.1 实验内容 hadoop配置文件介绍及修改 hdfs格式化 启动hadoop进程,验证安装 1.2 实验知识点 hadoop核心配置文件 文件系统的 ...