在我的一生中,我無法弄清楚如何僅將 SignalR 訊息發送給點擊“開始”按鈕的客戶端,而不是其他任何人。當我將它發送到“全部”時,一切正常,但我不知道如何在服務器上獲取 connectionID,然后將訊息發送到發起客戶端。這是我迄今為止所做的作業。如果您能告訴我如何僅使用呼叫客戶端來完成這項作業,我將不勝感激-
這是我的 Default.aspx 檔案
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SignalR5._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div><br /><br />
<asp:Button ID="btnGo" runat="server" Text="GO!!!" OnClick="btnGo_Click" OnClientClick="this.disabled=true;" UseSubmitBehavior="false" /><br /><br />
<asp:Label ID="lblLog" class="#log" runat="server" Text="Begin"></asp:Label> <br /> <br />
<asp:Label ID="lblConnectionID" runat="server" Text=""></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<script src="Scripts/jquery-3.4.1.js"></script>
<script src="Scripts/jquery.signalR-2.4.2.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function() {
var logger = $.connection.logHub;
logger.client.logMessage = function(msg) {
$("#MainContent_lblLog").html(msg);
};
$.connection.hub.start().done(function () {
var cid = $.connection.hub.id;
$("#MainContent_lblConnectionID").text("ConnectionID: " cid);
//alert("connection Id:" cid);
});
});
</script>
</asp:Content>
這是我的 Default.aspx.cs 檔案
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Diagnostics;
namespace SignalR5
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnGo_Click(object sender, EventArgs e)
{
//The timer is just to display how long each task takes.
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string strMessage = "Hello ";
LogHub.SendMessage(strMessage);
Thread.Sleep(2000);
strMessage = "(" stopWatch.Elapsed.Seconds " Seconds)<br>what's up bro? ";
stopWatch.Restart();
LogHub.SendMessage(strMessage);
Thread.Sleep(2500);
strMessage = "(" stopWatch.Elapsed.Seconds " Seconds)<br>Call me soon ";
stopWatch.Restart();
LogHub.SendMessage(strMessage);
Thread.Sleep(3200);
strMessage = "(" stopWatch.Elapsed.Seconds " Seconds)<br>See you later ";
stopWatch.Restart();
LogHub.SendMessage(strMessage);
Thread.Sleep(1800);
strMessage = "(" stopWatch.Elapsed.Seconds " Seconds)<br>Okay man. See you ";
stopWatch.Restart();
LogHub.SendMessage(strMessage);
Thread.Sleep(2900);
strMessage = "(" stopWatch.Elapsed.Seconds " Seconds)<br>We're all Done!";
lblLog.Text = strMessage;
stopWatch.Stop();
}
}
}
這是我的 Startup1.cs 檔案
using Microsoft.Owin;
using Owin;
using System;
using System.Threading.Tasks;
[assembly: OwinStartup(typeof(SignalR5.Startup1))]
namespace SignalR5
{
public class Startup1
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
這是我的 LogHub.cs 檔案
using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SignalR5
{
public class LogHub : Hub
{
// This is the only one working, but I don't want to send to all clients.
public static void SendMessage(string strMessage)
{
var hub = GlobalHost.ConnectionManager.GetHubContext("LogHub");
hub.Clients.All.logMessage(strMessage);
}
}
}
正如我所提到的,我真的很難弄清楚如何將它發送給“呼叫者”客戶端。它適用于“全部”。
uj5u.com熱心網友回復:
當呼叫你的“Go”按鈕時,你應該呼叫服務器中的“Go”方法,然后你就可以將資料發送給Caller類似的:
await hub.Clients.Caller.logMessage(message);
uj5u.com熱心網友回復:
每個連接到 SignalR 集線器的客戶端都有一個唯一的連接 ID。我們可以使用集線器背景關系的 Context.ConnectionId 屬性來檢索它。使用這個,我們可以只向那個特定的客戶端發送訊息。在此處了解更多相關資訊。
因此,要將訊息發送到特定客戶端,您將需要他們的連接 ID 來標識您要將訊息發送到哪個客戶端。
我在這里做了一個演示,用于向特定用戶發送訊息。這是樞紐類。這個發送方法會像往常一樣向所有連接的客戶端發送訊息,但我做的額外事情是,在開始時注冊他們的連接 ID 和用戶名,以便我以后可以訪問它們。
public static class UserHandler
{
// just remember when you will restart the app, object will get reset
public static HashSet<string> ConnectedIds = new HashSet<string>();
public static HashSet<string> ConnectedUsers = new HashSet<string>();
}
public void Send(string name, string message)
{
// registering the users
UserHandler.ConnectedIds.Add(Context.ConnectionId);
UserHandler.ConnectedUsers.Add(name);
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
此SendToSingleUser方法用于向特定用戶發送訊息,至于虛擬目的,我只是從串列中隨機選取第一個客戶端。如果您已經知道要將其發送給哪個用戶,那么您可以將 id 傳遞給該方法并在您的連接串列中查找該 ID,以確保它是一個有效的連接。
public void SendToSingleUser(string userName, string message)
{
string fromUserId = Context.ConnectionId;
//removing the currrent user ID & name
UserHandler.ConnectedIds.Remove(fromUserId);
UserHandler.ConnectedUsers.Remove(userName);
//taking a random user for sending message
string toUserId = UserHandler.ConnectedIds.First();
string toUserName = UserHandler.ConnectedUsers.First();
if (toUserId != null && fromUserId != null)
{
// send to
Clients.Client(toUserId).sendPrivateMessage(userName, message);
// send to caller user
Clients.Caller.sendPrivateMessage(userName, message);
}
}
aspx檔案:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Chat.aspx.cs" Inherits="SignalRChat.Chat" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SignalR Chat : Chat Page</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<link href="Content/style.css" rel="stylesheet" />
<link href="Content/font-awesome.css" rel="stylesheet" />
<script src="Scripts/jQuery-1.9.1.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="Scripts/date.format.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' encodedName
'</strong>: ' encodedMsg '</li>');
};
// Create a function that the hub can call to broadcast private messages
chat.client.sendPrivateMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' encodedName
'</strong>: ' encodedMsg '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
$('#CurrentUser').append($('#displayname').val());
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
//send to all user
$('#sendmessage').click(function () {
var msg = $("#message").val();
if (msg.length > 0) {
debugger;
var userName = $('#displayname').val();
chat.server.send(userName, msg);
$('#message').val('').focus();
}
});
//send to a sepcific user
$('#sendToSingleUser').click(function () {
var msg = $("#message").val();
if (msg.length > 0) {
debugger;
var userName = $('#displayname').val();
chat.server.sendToSingleUser(userName, msg);
$('#message').val('').focus();
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" ></asp:ScriptManager>
<div class="content-wrapper">
<div class="row">
<div class="container">
<label id="CurrentUser"> </label>
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="button" id="sendToSingleUser" value="Send Single User" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
</div>
</div>
<script src="Scripts/bootstrap.min.js"></script>
</form>
</body>
</html>
完整的演示可以在這里找到
注意:此演示與您發布的示例不同,我只是想告訴您如何實作通信。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/349157.html
