SignalR 单播

<template>
  <div style="display: flex;">
    <input type="text" v-model="messages" />
    <div>
      <button @click="sendMsg">sendMsg</button>
    </div>
  </div>
  <ul>
    <li v-for="(item, index) in messagesArray" :key="index">{{ item }}</li>
  </ul>
</template>

<script setup lang="ts">
import { HubConnectionBuilder } from "@microsoft/signalr";
import { ref } from "vue";

const messages = ref('');
const messagesArray = ref<string[]>([]);

//初始化signalr HubConnection对象
const connection = new HubConnectionBuilder()
  .withUrl("https://localhost:44342/hubs/chathub")//https://localhost:7260/chatHub
  .build();

//启动连接并发送消息测试
connection.start()
  .then(() => {
    const user = "1"; // 用户标识
    connection.send("SetUser", user);
  });

//注册web端方法以供后端调用
connection.on("ReceiveMessage", (message: string) => {
  console.log(message);
  messagesArray.value.push(message)
});

const sendMsg = async () => {
  const message = messages.value; // 获取消息文本

  // 替换为您要发送给的目标用户ID,可以通过一些界面操作或其他方式获取
  const targetUserId = "2"; // 示例:要发送给用户2

  // 发送消息,指定接收消息的用户
  await connection.send("SendMessageToUser", targetUserId, message).catch(function (err) {
    console.log(err);
  });

  messages.value = ""; // 清空输入框

}


</script>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
/// <summary>
    /// 聊天集线器
    /// </summary>
    [MapHub("/hubs/chathub")]
    public class ChatHub : Hub
    {

        private static Dictionary<string, string> userConnections = new Dictionary<string, string>();

        public Task SetUser(string user)
        {
            var connectionId = Context.ConnectionId;
            // 将连接 ID 与用户标识关联
            userConnections[user] = connectionId;

            return Task.CompletedTask;
        }


        public Task SendMessageToUser(string userId, string message)
        {
            var connectionId = userConnections[userId];
            if (connectionId != null)
            {
                return Clients.Client(connectionId).SendAsync("ReceiveMessage", message);
            }

            return Task.CompletedTask;
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值