我想用 Mssql 資料庫實作私人聊天系統。當我發送訊息時,此代碼作為公共代碼作業,訊息出現在所有客戶端。但我想要一對一的聊天系統。一位用戶輸入存盤在資料庫中的接收者 ID 和訊息文本,然后將訊息發送到 Receiver 。然后訊息出現在具有該接收者 ID 的接收者訊息區域中。
這是我的js代碼
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chathub").build();
//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user ":" msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
這是我的中心類
using MentorShip.Models;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MentorShip.Hubs
{
public class SignalRChat:Hub
{
Context c = new Context();
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage",user,message);
}
}
}
這是我的html代碼
<div class="container">
<div class="row"> </div>
<div class="row">
<div id="connectionId"></div>
<div class="col-2">Receiver Id</div>
<div class="col-4"><input type="text" id="userInput" /></div>
</div>
<div class="row">
<div class="col-2">Message</div>
<div class="col-4"><input type="text" id="messageInput" /></div>
</div>
<div class="row"> </div>
<div class="row">
<div class="col-6">
<input type="button" id="sendButton" value="Send Message" />
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
</div>
uj5u.com熱心網友回復:
要將訊息發送給特定用戶,您可以使用以下方法:
使用單用戶組。
您可以為每個用戶創建一個組,然后在您只想聯系該用戶時向該組發送訊息。每個組的名稱是用戶的名稱。如果用戶有多個連接,則每個連接 id 都會添加到用戶的組中。
例如,基于

通過 ConnectionID 發送訊息。
從上面的示例代碼中,在 OnConnectedAsyc 方法中,我們可以獲取 ConnectId 和 User Name,然后,您可以將它們存盤在資料庫中。然后,您可以在 ChatHub.cs 中添加 SendMessageToUser 方法。在該方法中,您可以根據接收者名稱查詢資料庫并找到connectionId,然后使用
Clients.Client("connectionId").SendAsync()方法將訊息發送給特定用戶。public Task SendMessageToUser(string sender, string receiver, string message) { //based on the receiver name to query the database and get the connection id return Clients.Client("connectionId").SendAsync("ReceiveMessage", sender, message); }
這里有一些相關的文章,你可以參考它們:

Using the following command in the Package Manager Console tools. More detail information, check 
Add the SignalR client library
- In Solution Explorer, right-click the project, and select Add > Client-Side Library.
- In the Add Client-Side Library dialog, for Provider select unpkg.
- For Library, enter @microsoft/signalr@latest.
- Select Choose specific files, expand the dist/browser folder, and select signalr.js and signalr.min.js.
- Set Target Location to wwwroot/js/signalr/, and select Install. LibMan creates a wwwroot/js/signalr folder and copies the selected files to it.
Create a SignalR hub.
In the Project folder, create a Hubs folder and add a ChatHub.cs file with the following code:
namespace SignalRApp.Hubs
{
//require using Microsoft.AspNetCore.SignalR;
//require using Microsoft.AspNetCore.Authorization;
[Authorize]
public class ChatHub : Hub
{
public override Task OnConnectedAsync()
{
Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
return base.OnConnectedAsync();
}
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
public Task SendMessageToGroup(string sender, string receiver, string message)
{
return Clients.Group(receiver).SendAsync("ReceiveMessage", sender, message);
}
}
}
Configure SignalR in the Startup.cs file. You could check 
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415877.html
標籤:
