<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;
}
}