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>
相关推荐
t_hj几秒前
Ajax案例
前端·javascript·ajax
未脱发程序员1 小时前
分享一款开源的图片去重软件 ImageContrastTools,基于Electron和hash算法
前端·javascript·electron
geovindu2 小时前
vue3: pdf.js 2.16.105 using typescript
javascript·vue.js·typescript·pdf
是梦终空3 小时前
Python毕业设计219—基于python+Django+vue的房屋租赁系统(源代码+数据库+万字论文)
python·django·vue·毕业设计·毕业论文·源代码·房屋租赁系统
ZHOU_WUYI3 小时前
用react实现一个简单的三页应用
前端·javascript·react.js
samroom4 小时前
Vue项目---懒加载的应用
前端·javascript·vue.js·性能优化
geovindu5 小时前
vue3: pdf.js5.2.133 using typescript
javascript·vue.js·typescript·pdf
白露与泡影5 小时前
聊聊四种实时通信技术:短轮询、长轮询、WebSocket 和 SSE
网络·websocket·网络协议
whatever who cares5 小时前
React 中 useMemo 和 useEffect 的区别(计算与监听方面)
前端·javascript·react.js
2501_915373885 小时前
打造一个 Markdown 编辑器:Electron 项目实战教程
javascript·electron·编辑器