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.
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 relatively new to SignalR, however, I have been through lots of documentation and can't get this to work.
I have a fully working Hub working within SignalR that is implemented as a console application. I have also got a client working as another console application. However, I would also like to be able to send messages to the server from an asp.net application.
I send messages like this:
_hub.Invoke("SendMessage", "ExampleMessage").Wait();
I want it to work so that on a:
<asp:button onclick="Signalr_FireEvent"> (Not Real Code)
It sends a message like the one on top.
Client Application Info:
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();
Assuming you have a Hub class in your console server such as:
public class MyHub : Hub
{
public void SendMessage(string message)
{
Console.WriteLine("Incoming message {0}", message);
}
}
you can access the server from a client web application either through javascript:
<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>
or code behind:
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();
}
Please, note you need to have the following packages installed in the web application:
Install-Package Microsoft.AspNet.SignalR.JS
Install-Package Microsoft.AspNet.SignalR.Client
As a complete reference, please read https://learn.microsoft.com/en-us/aspnet/signalr/overview/deployment/tutorial-signalr-self-host which my answer was based on.
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#.
This simple web socket example is returning a 200 error.
Edit: I am reposting the code in C# in hopes that more people will be able to advise me on why I'm having this issue.
I am running VS2012 Express, on my local IIS Machine, the project is configured for 4.5.1 framework and I have imported the Nuget Microsoft.Websockets package.
The three pieces of code I have included below are the only three pieces of code in the project and I have made no modifications to the rest of the project.
There is no break before the unexpected error, it does not break on open or on message on either side. The 200 comes up as an error in the chrome console, but there is no response preview.
Here is the client (index.htm):
<!doctype html>
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.8.1.js" type="text/javascript"></script>
<script src="test.js" type="text/javascript"></script>
</head>
<body>
<input id="txtMessage" />
<input id="cmdSend" type="button" value="Send" />
<input id="cmdLeave" type="button" value="Leave" />
<br />
<div id="chatMessages" />
</body>
</html>
and the client script (test.js):
$(document).ready(function () {
var name = prompt('what is your name?:');
var url = 'ws://' + window.location.hostname + window.location.pathname.replace('index.htm', 'ws.ashx') + '?name=' + name;
alert('Connecting to: ' + url);
var ws = new WebSocket(url);
ws.onopen = function () {
$('#messages').prepend('Connected <br/>');
$('#cmdSend').click(function () {
ws.send($('#txtMessage').val());
$('#txtMessage').val('');
});
};
ws.onmessage = function (e) {
$('#chatMessages').prepend(e.data + '<br/>');
};
$('#cmdLeave').click(function () {
ws.close();
});
ws.onclose = function () {
$('#chatMessages').prepend('Closed <br/>');
};
ws.onerror = function (e) {
$('#chatMessages').prepend('Oops something went wrong<br/>');
};
});
Here is the generic handler (ws.ashx):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.WebSockets;
namespace WebSockets
{
public class ws : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
context.AcceptWebSocketRequest(new TestWebSocketHandler());
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Here is the class (TestWebSocketHandler):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.Web.WebSockets;
namespace WebSockets
{
public class TestWebSocketHandler : WebSocketHandler
{
private static WebSocketCollection clients = new WebSocketCollection();
private string name;
public override void OnOpen()
{
this.name = this.WebSocketContext.QueryString["name"];
clients.Add(this);
clients.Broadcast(name + " has connected.");
}
public override void OnMessage(string message)
{
clients.Broadcast(string.Format("{0} said: {1}", name, message));
}
public override void OnClose()
{
clients.Remove(this);
clients.Broadcast(string.Format("{0} has gone away.", name));
}
}
}
It didn't come up with an error to any effect of this problem, but I found the error which Chrome failed to return alongside my 200 response.
I simply had to turn on the WebSocket protocol under Control Panel --> Programs --> Turn Windows Features on or Off --> IIS --> Application Development Features --> WebSocket Protocol.
At very least I've added a simple VB.NET WebSocket to the site.
Just make sure you have IIS 7+ and are running windows 8 in the 4.5 Framework...and to turn on the WebSocket feature above.
The 200 code is not an error, it's the HTTP OK response, which is what you want. Inspect the response using your browser, is there content in the response? Try to add a break point on your ws.onmessage to see if it fires up.
simply just check on the web socket protocol form add or remove programs
go to Control Panel
then click on add or remove programs
then Turn Windows Features on or Off
then IIS
then Application Development Features
then check the check box of WebSocket Protocol option
i tested it on Microsoft windows server 2012
I found this in wikipedia:
200 OK
Standard response for successful HTTP requests. The actual response will depend on the request method used. In a GET request, the response will contain an entity corresponding to the requested resource. In a POST request the response will contain an entity describing or containing the result of the action.
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...