This is a quick addition to my previous blog post on how to receive SignalR messages via PowerShell. Once you have established a connection in PowerShell to your SignalR hub you can easily them a message to the server via the ‘Invoke()’ method on the IHubProxy object.
In it you specify the name of the method you want to call and its arguments like this:
PS > # $s is a SignalR object PS > $s.GetType().FullName SignalRClient.Connection PS > $t = $s._hub.Invoke("SendMessageToServer", "tralala"); PS > $t Result : 9/5/2014 2:31:16 PM Id : 2 Exception : Status : RanToCompletion IsCanceled : False IsCompleted : True CreationOptions : None AsyncState : IsFaulted : False AsyncWaitHandle : System.Threading.ManualResetEvent CompletedSynchronously : False PS > $t.Result Friday, September 05, 2014 2:31:16 PM
The SignalR client object can be created and consumed as follows:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$eventName = "receiveMessage"; | |
Add-Type –Path ".\SignalRClient.dll" | |
$s = New-Object SignalRClient.Connection("http://localhost/", "commandhub"); | |
$s.Start($eventName); | |
while($true) { | |
$s.TryDequeue($eventName) | |
Start-Sleep –seconds 1 | |
} | |
# string TryDequeue(string eventName) | |
# string Dequeue(string eventName) | |
# string Dequeue(string eventName, int dwMillisecondsTotalWaitTime) | |
# string Dequeue(string eventName, int dwMillisecondsTotalWaitTime, int dwMilliSecondsWaitIntervall) | |
# System.Collections.Generic.List[string] DequeueAll(string eventName) |
In case your browser does not correctly render the Gist code you can view it directly at: https://gist.github.com/dfch/d598378f8a162a9bdf5b
The result of the operation is encapsulated in the “Result” property of the returned task object.
On the server side you just have to define a public method like this:
public string SendMessageToServer(string message) { System.Diagnostics.Debug.WriteLine("{0}@{1}: '{2}'", Context.User.Identity.Name, Context.ConnectionId, message); return DateTimeOffset.UtcNow.ToString("s"); }
… that’s all it takes.
Cool post! Cool for support or bugfixing issues! Here are some internals of SignalR, if you allow me to mention it here: http://robinsedlaczek.wordpress.com/2014/09/11/inside-signalr-addressing-clients-return-values-broken-connections-and-security/
Hi Robin, thanks for the link. Very good overview! Ronald
Thanks a lot for the feedback! :)