好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

微信小程序与AspNetCore SignalR聊天实例代码

微信小程序 与aspnetcore signalr实例

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

aspnetcore Signalr文档

小程序文档

写在之前

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

先上效果图

开始编码

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

 install-package microsoft.aspnetcore.signalr

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

?

1

2

3

4

5

public class onlineclient

{

  public string nickname { get; set; }

  public string avatar { get; set; }

}

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

public override async task onconnectedasync()

{

  var http = context.gethttpcontext();

  var client = new onlineclient()

  {

   nickname = http.request.query[ "nickname" ],

   avatar = http.request.query[ "avatar" ]

  };

  lock (syncobj)

  {

  onlineclients[context.connectionid] = client;

  }

  await base.onconnectedasync();

  await groups.addtogroupasync(context.connectionid, chatname);

  await clients.groupexcept(chatname, new [] { context.connectionid }).sendasync( "system" , $ "用户{client.nickname}加入了群聊" );

  await clients.client(context.connectionid).sendasync( "system" , $ "成功加入{chatname}" );

  }

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public override async task ondisconnectedasync(exception exception)

{

  await base.ondisconnectedasync(exception);

  bool isremoved;

  onlineclient client;

  lock (syncobj)

  {

  isremoved = onlineclients.tryremove(context.connectionid, out client);

  }

  await groups.removefromgroupasync(context.connectionid, chatname);

  if (isremoved)

  {

  await clients.groupexcept(chatname, new [] { context.connectionid }).sendasync( "system" , $ "用户{client.nickname}退出了群聊" );

  }

}

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

?

1

2

3

4

5

6

7

8

9

10

11

12

public async task sendmessage(string msg)

{

  var client = onlineclients.where(x => x.key == context.connectionid).select(x=>x.value).firstordefault();

  if (client == null )

  {

  await clients.client(context.connectionid).sendasync( "system" , "您已不在 聊天 室,请重新加入" );

  }

  else

  {

  await clients.groupexcept(chatname, new [] { context.connectionid }).sendasync( "receive" , new { msg, nickname = client.nickname, avatar = client.avatar });

  }

}

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

onload: function (options) {

  this .hubconnect = new hub.hubconnection();

  this .hubconnect.start( "https://chat.jingshonline.net/chat" , { nickname: app.globaldata.userinfo.nickname, avatar: app.globaldata.userinfo.avatarurl });

  this .hubconnect.onopen = res => {

  console.log( "成功开启连接" )

  }

  this .hubconnect.on( "system" , res => {

  wx.showmodal({

  title: '系统消息' ,

  content: res,

  })

  })

  this .hubconnect.on( "receive" , res => {

  centendata.push({

  content: res.msg,

  time: new date().tolocalestring(),

  head_owner: res.avatar,

  is_show_right: 0

  });

  this .setdata({

  centendata: centendata

  })

  })

  }

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

?

1

2

3

onunload: function () {

  this .hubconnect.close({ reason: "退出" })

}

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

?

1

this .hubconnect.send( "sendmessage" ,message);

完整的代码请去github https://github.com/liangshiw/signalrminiprogram-client/tree/master/sample
需要注意的是在打开小程序代码时,请修改project.config.json文件中的appid。

总结

以上所述是小编给大家介绍的微信小程序与aspnetcore signalr聊天实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://www.cnblogs.com/LiangSW/p/9415246.html

查看更多关于微信小程序与AspNetCore SignalR聊天实例代码的详细内容...

  阅读:52次