use*_*435 2 asp.net-mvc windows-services signalr
我在 Windows 服务中有一个 SignalR 客户端,它成功调用 MVC 应用程序中的服务器方法。首先是服务器代码:
public class AlphaHub : Hub
{
public void Hello(string message)
{
// We got the string from the Windows Service
// using SignalR. Now need to send to the clients
Clients.All.addNewMessageToPage(message);
// Send message to Windows Service
}
Run Code Online (Sandbox Code Playgroud)
和
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.MapSignalR("/signalr", new HubConfiguration());
}
}
Run Code Online (Sandbox Code Playgroud)
Windows 服务客户端是:
protected override async void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
try
{
var hubConnection = new HubConnection("http://localhost.com/signalr", useDefaultUrl: false);
IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub");
await hubConnection.Start();
await alphaProxy.Invoke("Hello", "Message from Service");
}
catch (Exception ex)
{
eventLog1.WriteEntry(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
它向 MVC 服务器发送一条消息。现在我想从服务器到客户端调用另一种方式。客户端编程指南具有以下代码示例,这些代码示例不起作用,因为这不是桌面。
WinRT Client code for method called from server without parameters (see WPF and Silverlight examples later in this topic)
var hubConnection = new HubConnection("http://www.contoso.com/");
IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");
stockTickerHub.On("notify", () =>
// Context is a reference to SynchronizationContext.Current
Context.Post(delegate
{
textBox.Text += "Notified!\n";
}, null)
);
await hubConnection.Start();
Run Code Online (Sandbox Code Playgroud)
如何调用客户端的方法?
.NET 客户端代码看起来不错。您可以简单地摆脱,Context.Post因为您的客户端在 Windows 服务内运行并且不需要 SyncContext:
protected override async void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
try
{
var hubConnection = new HubConnection("http://localhost.com/signalr", useDefaultUrl: false);
IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub");
stockTickerHub.On("Notify", () => eventLog1.WriteEntry("Notified!"));
await hubConnection.Start();
await alphaProxy.Invoke("Hello", "Message from Service");
}
catch (Exception ex)
{
eventLog1.WriteEntry(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以从服务器上的 AlphaHub 内部调用“Notify”回调,如下所示:
public class AlphaHub : Hub
{
public void Hello(string message)
{
// We got the string from the Windows Service
// using SignalR. Now need to send to the clients
Clients.All.addNewMessageToPage(message);
// Send message to the Windows Service
Clients.All.Notify();
}
Run Code Online (Sandbox Code Playgroud)
因为我们使用的是 ,所以任何客户端都可以收听这些通知Clients.All。如果您想避免这种情况,您需要某种方法来验证您的 Windows 服务并获取其ConnectionId. 完成后,您可以像这样发送到 Windows 服务:
Clients.Client(serviceConnectionId).Notify();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3085 次 |
| 最近记录: |