ASP.NET Core SignalR向部分客户端发消息

筛选客户端

  1. 客户端筛选的3个参数:ConnectionId、组和用户Id(它对应ClaimTypes.NameIdentifier的Claim)。
  2. Hub的Groups属性为IGroupManager属性,可以对组成员进行管理。查看类型的成员。
  3. Hub的Clients属性为IHubCallerClients类型,可以对连接到当前集线器的客户端进行筛选。查看类型的成员。
  4. IClientProxy类型。无法知道具体有哪些客户端调用SendAsync()方法向筛选的客户端发送消息。
  5. 实现聊天室私聊。

IGroupManager 接口 (Microsoft.AspNetCore.SignalR) | Microsoft Learnhttps://learn.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.signalr.igroupmanager?view=aspnetcore-9.0

IHubCallerClients 接口 (Microsoft.AspNetCore.SignalR) | Microsoft Learnhttps://learn.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.signalr.ihubcallerclients?view=aspnetcore-9.0

cs 复制代码
public async Task SendPrivateMsg(string UserName, string message)
{
    var user = await userManager.FindByNameAsync(UserName);
    long userId = user.Id;
    string currentUserName = this.Context.UserIdentifier;
    await this.Clients.User(userId.ToString()).SendAsync("ReceivePrivateMsg", currentUserName, message );
}
javascript 复制代码
<template>
  <div>公屏:
    <input type="text" v-model="state.userMessage" v-on:keypress="txtMsgOnkeypress" />
  </div>
  <div>私聊:
    目标用户名:<input type="text" v-model="state.privateMsg.toUserName" />
    <input type="text" v-model="state.privateMsg.msg" v-on:keypress="txtPrivateMsgOnkeypress" />
  </div>
  <div>
    用户名<input type="text" v-model="state.loginData.username" />
    密码<input type="password" v-model="state.loginData.password" />
    <button v-on:click="loginClick">登录</button>
  </div>
  <div>
    <ul>
      <li v-for="(msg, index) in state.messages" :key="index">{
  
  { msg }}</li>
    </ul>
  </div>
</template>

<script>
import { reactive } from 'vue';
import * as signalR from '@microsoft/signalr';
import axios from 'axios';

let connection;
export default {
  name: 'Login',
  setup() {
    //创建响应式对象
    const state = reactive({
      accessToken: "", userMessage: "", messages: [],
      loginData: { userName: "", password: "" },
      privateMsg: { toUserName: "", msg: "" }
    });

    //SignalR连接
    const startConn = async function () {
      const transport = signalR.HttpTransportType.WebSockets;
      const options = { skipNegotiation: true, transport: transport };
      options.accessTokenFactory = () => state.accessToken;
      connection = new signalR.HubConnectionBuilder()
        .withUrl('https://localhost:7181/MyHub', options)
        .withAutomaticReconnect().build();
      try {
        await connection.start();
      } catch (err) {
        alert(err);
        return;
      }

      //注册ReceivePublicMessage事件,接收消息,添加到messages数组
      connection.on('ReceivePublicMessage', msg => {//监听服务器端发送过来的信息
        state.messages.push(msg);
      });
      //注册SendPrivateMessage事件,接收消息,添加到messages数组
      connection.on('ReceivePrivateMsg',(fromUserName,msg) => {//监听服务器端发送过来的信息
        state.messages.push(fromUserName+"私聊说:"+msg);
      });
    }

    //点击登录
    const loginClick = async function () {
      const resp = await axios.post('https://localhost:7181/api/Demo/Login', state.loginData)
        .then((response) => {
          state.accessToken = response.data;
          startConn()
        })
    };

    //按下回车键发送消息,调用SendPublicMessage方法,发送消息,清空输入框
    const txtMsgOnkeypress = async function (e) {
      if (e.keyCode != 13) return;
      await connection.invoke("SendPublicMessage", state.userMessage);
      state.userMessage = "";
    };

    //按下回车键发送私聊消息,调用SendPrivateMessage方法,发送消息,清空输入框
    const txtPrivateMsgOnkeypress = async function (e) {
      if (e.keyCode != 13) return;
      await connection.invoke("SendPrivateMsg", state.privateMsg.toUserName,state.privateMsg.msg);
      state.privateMsg.msg = "";
    };

    //返回响应式对象和方法
    return { state, txtMsgOnkeypress,txtPrivateMsgOnkeypress, loginClick };
  },
}
</script>
相关推荐
保持学习ing1 小时前
帝可得 - 设备管理
javascript·vue.js·elementui
烛阴2 小时前
自动化测试、前后端mock数据量产利器:Chance.js深度教程
前端·javascript·后端
每天都有好果汁吃2 小时前
基于 react-use 的 useIdle:业务场景下的用户空闲检测解决方案
前端·javascript·react.js
占星安啦3 小时前
一个html实现数据库自定义查询
java·前端·javascript·数据库·动态查询
老K(郭云开)4 小时前
allWebPlugin中间件VLC专用版之截图功能介绍
前端·javascript·chrome·中间件·edge
Rousson4 小时前
硬件学习笔记--65 MCU的RAM及FLash简介
开发语言·前端·javascript
萌萌哒草头将军4 小时前
🏖️ TanStack Router:搜索参数即状态!🚀🚀🚀
javascript·vue.js·react.js
小疯仔5 小时前
使用el-input数字校验,输入汉字之后校验取消不掉
android·开发语言·javascript
wangbing11256 小时前
开发指南120-表格(el-table)斑马纹
javascript·vue.js·elementui
Joe5566 小时前
antDesignVue中a-upload上传组件的使用
前端·javascript