This is my HTML:
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.khaosHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (message) {
// Html encode display name and message.
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li>' + encodedMsg + '</li>');
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
console.log("sending");
// Call the Send method on the hub.
chat.server.send("something");
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
My Hub:
public class KhaosHub : Hub
{
public void Send(string message)
{
Clients.All.broadcastMessage(message);
}
}
When I click #sendmessage my Send method in KhaosHub is triggered which I have verified using a breakpoint and my message does get sent to the div via broadcastMessage.
Note: I've not included my call to app.MapSignalR in the example above as I know it's working from the client side.
The issue I have is when I call broadcastMessage from some back end code it doesn't work. I am calling it via:
var context = GlobalHost.ConnectionManager.GetHubContext<KhaosHub>();
context.Clients.All.broadcastMessage("some message");
When I debug the Clients.All property, I can't see any clients (I don't know if I should be able to but thought I'd add that information.
Any ideas?
EDIT: This is my startup class for the hub:
[assembly: OwinStartup(typeof (Startup))]
namespace CC.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Thanks for the question. Following up on the comments I have tracked my own problem down also to not getting the correct hubcontext from the GlobalHost.ConnectionManager.
To solve this I specifically set a DependencyResolver on the GlobalHost and passing this Resolver to the HubConfiguration used to MapSignalR.
In code that is:
Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver =
New Microsoft.AspNet.SignalR.DefaultDependencyResolver
app.MapSignalR(
New Microsoft.AspNet.SignalR.HubConfiguration With
{.Resolver = Microsoft.AspNet.SignalR.GlobalHost.DependencyResolver})
You may want to convert this VB.Net code to C#.
Related
I have the Http server (written in D lang) with endpoint for POST method. I want to stream some commands to that method from my non web client written in .Net, and durring that streaming it would be good for me to listen also for response from this server in case something went wrong. And here is the problem, it seems that I should end streaming (or send zero tcp message) to get any response.
Thanks for Wireshark I know that it behaves like this:
I send message to server with headers
Server answer me with ACK
Next, I send my message with some coordinates
"18\r\n[{"x":0.5,"y":0.5,"z":0}\r\n"
Server answer with ACK and HTTP Continue status
Then I stream some commands to server and it answer me with ACK for each command
Next, I wait a little bit, the server send me HTTP Request Time-out.
BUT, my application will not get this and would think that everything is fine.
One version of implementation:
public async Task Start()
{
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;
var json = GetData();
StreamWriter writer = null;
var content = new PushStreamContent(async (stream, httpContent, transportContext) =>
{
writer = new StreamWriter(stream);
writer.AutoFlush = true;
await writer.WriteLineAsync("[" + json);
});
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var message = new HttpRequestMessage(HttpMethod.Post, url);
message.Content = content;
Task.Run(async () =>
{
var result = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead);
Console.WriteLine(result.StatusCode);
});
while (true)
{
if(Console.ReadKey().KeyChar == 'a')
{
await writer.WriteLineAsync($",{json}");
}
}
}
Your scenario looks a good match for SignalR.
Basically, SignalR is an open-source library that simplifies adding real-time web functionality to apps. Real-time web functionality enables server-side code to push content to clients instantly.
You can find a sample using SignalR 2 with non-Core version bellow:
First, create the following basic structure in server side:
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
Now you need to create the following structure in client side:
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-3.1.1.min.js" ></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<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>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
You can have more info about SignalR here.
I'm familiar with WebMethods and PageMethods to call Server side methods from the client side without refreshing page.
I'm achieving to Invoke Server-side method (present inside index.aspx.cs).
Here is what i'm trying:
Server Side Created Hub class:
public class MyHub : Hub
{
public void RefreshData(string imessage)
{
Clients.All.displayData(imessage);
}
}
Client side:
<script>
var isconnected = false;
(function () {
$.connection.myHub.client.displayData = function (thisdata) {
$('ul').append('<li>' + thisdata + '</li>');
};
$("#btnadd").click(function () {
if (isconnected) {
$.connection.myHub.server.refreshData($("#txtval").val());
}
});
$.connection.hub.start()
.done(function () {
isconnected = true;
})
.fail(function () {
isconnected = false;
});
})();
</script>
Above things are working fine, Client is calling Server-side's RefreshData Method and Server is passing message to the Client-side's displayData method.
My Question is: As same as AJAX WebMethod () .. Is it possible to call any method of index.aspx.cs (not inside the MyHub class) ?
If i talk about calling Client-side method from the index.aspx.cs, then we can try:
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.displayData(imessage);
But if i search about listening client side's method call from any page.aspx.cs, i'm not getting anything..
I hope i have explained the issue, if not..please excuse me..
No, you cannot call aspx.cs method (outside Hub) using SignalR connection. What is extact scenario for which you need to invoke aspx.cs method using SignalR? As mentioned by you, use ajax for invoking aspx.cs method.
Infact for code snippet mentioned above, ajax is best suited (not
SignalR).
SignalR is mainly used when you need open connection between client and server (ex- using websocket, one of transport option support with SignalR). It is more appropriate if you need to push message from server to client without client requesting it.
// Invoke this from server when server want to push some information to client without client requesting this information
$.connection.myHub.client.updateData = function (thisdata) {
$('ul').append('<li>' + thisdata + '</li>');
};
I have a request from client to Server using SignalR-2.2.1. After that request, Server will send the results back to the caller.
Here is my JavaScript code :
$(document).ready(function () {
var myHub = $.connection.signalHub;
myHub.client.receive = function (tmp) {
var obj = $.parseJSON(tmp);
//do something
};
$.connection.hub.start().done(function () {
$('#xxxxx').click(function () {
var form = $("form");
form.submit();
myHub.server.sendSomething();
});
}).fail(function (reason) {
//do something
});
});
And here is the code from my Server Side
public partial class SignalHub : Hub
{
public void SendSomething()
{
Clients.All.receive(MyJson);
}
}
When I use Clients.All function, it works perfectly fine. But what I want is the server only send the result back to the caller (the one that send the request).
So I change Clients.All.receive(MyJson) to Clients.Caller.receive(MyJson). After I change it, now the client doesnt update the content. Do I need to specify my receive function in client side that it would receive something different?
My guess is that since you are calling form.submit(); you are probably navigating away from the page or possibly reloading it, in that sense a new connection with a different "connectionId" is established between the new/reloaded page, thus the message intended for Client.Caller is lost since it is associated with the connection established on the page that you navigated away from or refreshed.
You might want to consider posting your form-data using AJAX instead of a full form submit.
So, I have a SignalR self hosted console application and a website running on WAMP. Everything works just fine when I'm using localhost as domain-name. Obviously this only works locally.
I want it to work on other computer too. So I have tried to change localhost to my local ip, both in the c# console application, and also on the website. The console application crashes when I have my local ip, with the error :
An unhandled exception of type
'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
I have also tried to use * instead of localhost in the console application. Like this:
string url = "http://*:8080/servers/2/";
Same goes there, it crashes. What am I doing wrong?
Console application code:
namespace SignalRSelfHost
{
class Program
{
public static IPAddress ipAd { get; set; }
public static TcpListener myList { get; set; }
static void Main(string[] args)
{
// This will *ONLY* bind to localhost, if you want to bind to all addresses
// use http://*:8080 to bind to all addresses.
// See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
// for more information.
string url = "http://localhost:8080/servers/2/";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
// EnableJSONP = true
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
}
}
public class MyHub : Hub
{
public void Send(string message)
{
Clients.All.addMessage(message);
}
}
}
And my website's code:
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion"></ul>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="/assets/js/jquery-1.6.4.min.js"></script>
<!--Reference the SignalR library. -->
<script src="/assets/js/jquery.signalR-2.0.3.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="http://localhost:8080/servers/<?php echo $server->row()->id; ?>/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
var url = "http://localhost:8080/servers/<?php echo $server->row()->id; ?>/signalr";
//Set the hubs URL for the connection
$.connection.hub.url = url;
// Declare a proxy to reference the hub.
var chat = $.connection.myHub;
// Create a function that the hub can call to broadcast messages.
chat.client.addMessage = function (message) {
// Html encode display name and message.
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li>' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
//$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
//$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
Solved it by running the program as administrator.
I have implemented SignalR for my Windows Azure project. I have two clients - Javascript/HTML client in my web role and a console application in my project. And Web role is my SignalR server. When i put the web role and the console application as the start up projects, the messages i send from the HTML client are sent to the console application. But when i put the Cloud project and the console application as the start up projects, the messages from the HTML client are not being sent to the console application. Its really weird, i dont know what could be the difference between the two which is causing the problem.
And if i put a background thread in my web role which will send messages to connected clients periodically, it works on both occasions, i mean the console app and the HTML client are receiving messages irrespective of the start up projects.
Please let me know if you have any idea what the problem is
My Hub:
public class BroadcastHub : Hub
{
public void Send(PersistedAudioRecord record)
{
// Call the BroadcastAudio method to update clients.
Clients.All.BroadcastAudio(record);
}
}
My HTML/Javascript client:
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var broadcast = $.connection.broadcastHub;
// Create a function that the hub can call to broadcast messages.
broadcast.client.broadcastAudio = function (record) {
// Html encode user name, channel and title.
var encodedName = $('<div />').text(record.Username).html();
var encodedChannel = $('<div />').text(record.Channel).html();
var encodedTitle = $('<div />').text(record.Title).html();
// Add the broadcast to the page.
$('#broadcasts').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedChannel + '</strong>: ' + encodedTitle + '</li>');
};
// Get the user name.
$('#displayname').val(prompt('Enter your name:', ''));
// Get the Channel name to which you want to broadcast.
$('#channelname').val(prompt('Enter Channel:', ''));
// Set initial focus to message input box.
$('#title').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendbroadcast').click(function () {
// Call the Send method on the hub.
var broadcastMessage = {}
broadcastMessage.Username = $('#displayname').val();
broadcastMessage.Channel = $('#channelname').val();
broadcastMessage.Title = $('#title').val();
broadcast.server.send(broadcastMessage);
// Clear text box and reset focus for next broadcast.
$('#title').val('').focus();
});
});
});
</script>
My Console app client:
class Program
{
static void Main(string[] args)
{
HubConnection connection = new HubConnection("http://localhost:35540/");
IHubProxy proxy = connection.CreateHubProxy("BroadcastHub");
proxy.On<AudioRecord>("BroadcastAudio", BroadcastAudio);
connection.Start().Wait();
Console.ReadLine();
}
static void BroadcastAudio(AudioRecord record)
{
Console.WriteLine("Broadcast: {0} {1} {2}", record.Username, record.Channel, record.Title);
}
}
Background Thread:
public class BackgroundThread
{
private static Random _random = new Random();
public static void Start()
{
ThreadPool.QueueUserWorkItem(_ =>
{
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<BroadcastHub>();
while (true)
{
PersistedAudioRecord record = new PersistedAudioRecord();
record.Channel = _random.Next(10).ToString();
record.Username = new string('a', Convert.ToInt32(record.Channel));
record.Title = new string('b', Convert.ToInt32(record.Channel));
try
{
hubContext.Clients.All.BroadcastAudio(record);
}
catch (Exception ex)
{
System.Diagnostics.Trace.TraceError("SignalR error thrown: {0}", ex);
}
Thread.Sleep(TimeSpan.FromSeconds(2));
}
});
}
}
I tried this scenario with my application and I was able to send messages from a webrole to a console application. Is it possible to zip your project and send it to see if this reproes...