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.
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 trying to create a simple C# websocket server with websocket-sharp
and I followed the official guide but I got some peculiar reply instead.
C# Snippet
using System;
using WebSocketSharp.Server;
namespace WebSocketSharp
{
class MainClass
{
public static void Main(string[] args)
{
startServer();
}
public static void startServer()
{
var ws = new WebSocketServer(System.Net.IPAddress.Any, 8181);
ws.Start();
Console.WriteLine("Server started");
Console.ReadKey(true);
ws.Stop();
Console.WriteLine("Server stopped");
}
}
}
When I tried to connect my client (HTML) to the server, I got a message
WebSocket connection to 'ws://127.0.0.1:8181/' failed: Error during WebSocket handshake: Unexpected response code: 501
and this showed up at my terminal at the same time
According to HTTP Protocol, code 501 means
The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.
This is my client code and I believe it conforms with the request method.
<!doctype html>
<head>
</head>
<body>
<form>
<input id="textField1" type="text" style="margin: 0 5px; width: 200px; height: 40px;" placeholder="Enter data">
<button id="sendTextField1" type="button" class="btn btn-info">Send</button>
</form>
<script type="text/javascript">
var start = function () {
var wsImpl = window.WebSocket || window.MozWebSocket;
window.ws = new wsImpl('ws://127.0.0.1:8181/');
ws.onmessage = function (evt) {
console.log(evt.data);
};
ws.onopen = function () {
console.log("Connected");
};
ws.onclose = function () {
console.log("Closed");
};
document.getElementById("sendTextField1").onclick = function() {
sendToSocket(document.getElementById('textField1').value);
};
function sendToSocket(value){
console.log("Sending value to socket " + value + " ");
ws.send(value);
};
}
window.onload = start;
Can anyone tell me where is my mistake?
I think the problem is you're not adding a behavior to the server. I did the "laputa" thing that is mentioned in the docs here: https://github.com/sta/websocket-sharp.
Don't forget to connect to the right endpoint. In the example the endpoint is "/laputa", so you have to connect in your javascript like:
var socket = new WebSocket('ws://127.0.0.1:8081/laputa');
You need to add a class inherited from WebSocketBehavior, I`m not sure the library will work without it.
The example did not work for me though, I had to call server.Start() before adding behaviors.
I thought this would be helpful as the core of the question is on how to setup the WebSocket server and having some basic exchange with a client. This minimal code creates both, a local Server & Client, who perform a primitive exchange in purpose of demonstrating the basic communication between them:
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace ConsoleApp1
{
public class ConsoleApplication
{
public class ServerService : WebSocketBehavior
{
protected override void OnMessage(MessageEventArgs e)
{
Console.WriteLine("I, the server, received: " + e.Data);
Send("I, the server, send you this!");
}
}
public static void Main(string[] args)
{
// Server
var wssv = new WebSocketServer(1236);
wssv.AddWebSocketService<ServerService>("/service");
wssv.Start();
Console.WriteLine("Server is setup.");
Console.ReadLine();
// Client
var ws = new WebSocket("ws://127.0.0.1:1236/service");
ws.OnMessage += (sender, e) => Console.WriteLine("I, the client, received: " + e.Data);
ws.Connect();
Console.WriteLine("Client is setup.");
Console.ReadLine();
// The client sends a message to the server:
ws.Send("Server, please send me something!");
Console.ReadLine();
}
}
}
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.
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.