gpt4 book ai didi

c# - SignalR 在 asp.net 和控制台应用程序之间进行通信

转载 作者:太空宇宙 更新时间:2023-11-03 20:54:34 25 4
gpt4 key购买 nike

我是 SignalR 的新手,但是,我已经阅读了大量文档,但无法让它发挥作用。

我有一个在 SignalR 中运行的功能完备的集线器,该集线器作为控制台应用程序实现。我还有一个客户端作为另一个控制台应用程序工作。但是,我还希望能够从 asp.net 应用程序向服务器发送消息。

我这样发送消息:

_hub.Invoke("SendMessage", "ExampleMessage").Wait();

我希望它能在以下情况下工作:

<asp:button onclick="Signalr_FireEvent"> (Not Real Code)

它会像上面的那样发送一条消息。

客户端应用信息:

IHubProxy _hub;
string url = @"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("Hub");
connection.Start().Wait();
_hub.On("ReceiveMessage", x => Console.WriteLine(x)); //On Receive Message Write To Console

_hub.Invoke("SendMessage", "$").Wait(); //Send LoggedIn Message once connected to server

string line = null;
while ((line = System.Console.ReadLine()) != null)
{
_hub.Invoke("SendMessage", line).Wait();
}
Console.Read();

最佳答案

假设您的控制台服务器中有一个 Hub 类,例如:

public class MyHub : Hub
{
public void SendMessage(string message)
{
Console.WriteLine("Incoming message {0}", message);
}
}

您可以通过 javascript 从客户端 Web 应用程序访问服务器:

<form runat="server">
<div>
<input type="button" id="sendmessage" value="Send from javascript" />
<asp:Button ID="Button1" runat="server" Text="Send from code behind" OnClick="Button1_Click" />
</div>
</form>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.6.4.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.3.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="http://localhost:8080/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
//Set the hubs URL for the connection
$.connection.hub.url = "http://localhost:8080/signalr";

// Declare a proxy to reference the hub.
var _hub = $.connection.myHub;

// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the SendMessage method on the hub.
_hub.server.sendMessage("$");
});
});
});
</script>

或隐藏代码:

protected void Button1_Click(object sender, EventArgs e)
{
//Set the hubs URL for the connection
string url = "http://localhost:8080/signalr";

// Declare a proxy to reference the hub.
var connection = new HubConnection(url);

var _hub = connection.CreateHubProxy("MyHub");

connection.Start().Wait();

_hub.Invoke("SendMessage", "$").Wait();
}

请注意,您需要在网络应用程序中安装以下软件包:

Install-Package Microsoft.AspNet.SignalR.JS

Install-Package Microsoft.AspNet.SignalR.Client

作为完整引用,请阅读 https://learn.microsoft.com/en-us/aspnet/signalr/overview/deployment/tutorial-signalr-self-host我的回答基于此。

关于c# - SignalR 在 asp.net 和控制台应用程序之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51774998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com