I'm working on a project in MVC of chat with SignalR.
I have bought a web host with Windows Server 2012 R2 with IIS8 and framework 4.5 and websockets enabled (more server details: http://www.register.it/hosting/windows/compare.html, I've got smart pack).
What my test application does is just a test for connect to hub in main page (I have another application, but I want to figure out what is the problem with minimum code possible), and when the client try to connect, this is the error:
WebSocket connection to 'ws://otaku2gether.com/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=VHGrwNoDXPMMbtM5dx1e2gF08%2FRWnVkbKUKjGkZkhE4I0p%2FpIFehvooO1shzCxkjU5f308%2FjleQIErTFsZqqe%2B1R4T2GRwMlO0IQbiZE9Z245YZcg6ipRF3cT1TOrqWB&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&tid=10' failed: Error during WebSocket handshake: 'Sec-WebSocket-Accept' header is missing
The view is really simple:
#section scripts {
<script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
var roomvar = $.connection.chatHub;
$.connection.hub.logging = true;
roomvar.client.sendBroadcast = function (message) {
alert(message);
};
$.connection.hub.start();
});
</script>
}
and the others prerequisites is done(helped also by the main tutorial https://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc ) like startup, and hub.
Does someone have some suggestions?
Related
I have implemented a Blazor application with Signalr (server side flavour) which works fine locally, but when I deploy it to a server with IIS it throws:
2021-03-12 08:41:44.7882|100|WARN|Microsoft.AspNetCore.Components.Server.Circuits.RemoteRenderer|Unhandled exception rendering component: Response status code does not indicate success: 400 (Bad Request). System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request).
Here's the configuration code in Startup.cs:
var url = applicationRoot + "/messagehub";
logger.LogInformation("Message hub url: " + url);
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapRazorPages();
endpoints.MapHub<MessageHub>(url);
endpoints.MapFallbackToPage("/_Host");
endpoints.MapControllers();
});
and here's the HubConnectionBuilder's code:
Uri url = navigationManager.ToAbsoluteUri(linksSettings.ApplicationRoot + "/messagehub");
logger.LogInformation("Message hub url: " + url);
hubConnection = new HubConnectionBuilder()
.WithUrl(url)
.Build();
One thing I've noticed is that if I navigate to https://localhost:55514/messagehub I get
Connection ID required
but when I navigate to https://my-apps.com/sub-app/messagehub I get
Sorry, nothing here
which comes from the file App.razor
<Router AppAssembly="#typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="#routeData"></RouteView>
</Found>
<NotFound>
<p>Sorry, nothing here</p>
</NotFound>
</Router>
I don't know if this is because the hub never was instantiated properly or if there's a routing problem.
As you can see I have different application roots locally and on server. Maybe this has something to do with the problem?
Please help!
I am working on project of Ionic with angular and AspNet with SignalR that have chat module.
I use SignalR for Chat.It's working smoothly but some time i am getting error as per below screen shot and because of that it's get stop working at all.
I have hosted my service on IIS and creating proxy and communicating with client and server. Here is sample
(function () {
angular
.module('app')
.factory('SignalRFactory', SignalRFactory);
SignalRFactory.$inject = ['$rootScope', 'Hub', 'ionicToast'];
function SignalRFactory($rootScope, Hub, ionicToast) {
var signalRLocal = this;
var serverURL = 'https://serivcerURL.com/signalr';
//Hub setup
var hub = new Hub('CommunicationHub', {
rootPath: serverURL,
listeners: {
'send': function (data) {
console.log("send " + data);
}
},
errorHandler: function (error) {
//Here i am getting that websocket closed error
console.error(error);
}
});
signalRLocal.Connect = function (user) {
console.log("SignalR Connecting as :" + user.UserName);
hub.invoke('connect', user);
};
return signalRLocal;
}
})();
I have hosted service on IIS. I search for the solution and find something like this link
I also try with above link solution by using "long Polling" as per below
Hub.connection.start({ transport: 'longPolling' });
But i don't want to use "long Polling" at all.
So can someone help me to figure out this issue without use of 'long Polling'.
Can someone tell me what configuration i have to do at client side or at IIS level.
As we said in comments, SignalR client will try to reconnect after the connection is lost. Besides, many factors (such as physical network interruption, client browser failure, server offline etc) can cause the connection lost, this article explains some disconnection scenarios, you can refer to it and find the possible causes of the issue.
Besides, as I mentioned in comment, you can call the Start method from your Closed event handler (disconnected event handler on JavaScript clients) to start a new connection to make client automatically re-establish a connection after it has been lost.
edit:
The connection to ws://localhost:3156/signalr/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=g8vpRv9ncVDjPIYB9UuEpAAILEaOcTMTG9p46IA24 was interrupted while the page was loading.
Under "Client disconnection scenarios" section in the article, you can find:
In a browser client, the SignalR client code that maintains a SignalR connection runs in the JavaScript context of a web page. That's why the SignalR connection has to end when you navigate from one page to another, and that's why you have multiple connections with multiple connection IDs if you connect from multiple browser windows or tabs. When the user closes a browser window or tab, or navigates to a new page or refreshes the page, the SignalR connection immediately ends because SignalR client code handles that browser event for you and calls the Stop method.
I am trying same and my client is in vue.js. I have changed below in vue.config.js
module.exports = {
devServer: {
proxy: {
'/hub': {
target: 'https://localhost:5001',
changeOrigin: false,
secure: false,
headers: {
'x-forwarded-proto': 'http',
},
},
},
},
}
Previously i am trying 'x-forwarded-proto': 'https', when I changed to http its work.
https://localhost:5001 is my .net endpoint and http://localhost:8080 is my vue enpoint
Changed in Startup.csbelow,
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<CardsHub>("/hub/cardsHub");
});
Added below code in vue component
this.connection = new signalR.HubConnectionBuilder()
.withUrl('/hub/cardsHub')
.build()
In my case the culprit was the wrong version of Microsoft.AspNetCore.SignalR.Common
the default one installed was 5.0.3
but I was targeting 3.1.0
Downgrading to 3.1.12 fixed the issue with the connection.
First off im using the JDare/ClankBundle
I'm following these instruction to call a function from the client side
https://github.com/JDare/ClankBundle/blob/master/Resources/docs/RPCSetup.md
I keep gettting this error on the console "RPC Error [object Object] undefined"
I noticed that it doesn't matter if I mispell the notify_func function, it still throws the same error.
I don't know what im doing wrong, but I assume the function isn't found to begin with?
This is the client side (Twig)
The websocket connects succesfully
<script type="text/javascript">
var myClank = Clank.connect('ws://localhost:9999');
myClank.on("socket/connect", function(session){
alertify.success("Connected to websocket server");
//this will call the server side function "Sample::addFunc"
session.call("notify/notify_func",[2,5])
.then( //using "then" promises.
function(result) //the function for a valid result
{
alertify.log("RPC Valid! "+result);
},
function(error, desc) // the function to handle an error
{
alertify.log("RPC Error"+" "+error+" "+desc);
}
);
});
myClank.on("socket/disconnect", function(error){
alertify.error("Disconnect for "+error.reason+" with code "+error.code);
});
</script>
This is the server side
<?php
namespace Gabriel\NotificationsBundle\RPC;
use Ratchet\ConnectionInterface as Conn;
class PostCommentNotificationService
{
public function notifyFunc(Conn $conn,$params)
{
return array("result"=>array_sum($params));
}
}
This is the config
#services.yml
services:
notifications.newcommentpost:
class: Gabriel\NotificationsBundle\RPC\PostCommentNotificationService
#config.yml
# Clank Configuration
clank:
web_socket_server:
port: 9999 #The port the socket server will listen on
host: localhost #(optional) The host ip to bind to
rpc:
-
name: "notify" #Important! this is the network namespace used to match calls to this service!
service: "notifications.newcommentpost" #The service id.
I had a very similar problem.
I found out that stopping and restarting the built-in websocket server solved the problem. Every modification done on the websocket code requires the websocket server to be restarted in order for these changes to take place...
php app/console clank:server
All the signalR examples shows
<script src="/signalr/hubs" type="text/javascript"></script>
without explainning enough what is it used for .
For the Html page it is a location of folder . and there is no script there.
Why and how this line is being used ?
The /signalr/hubs page is a JavaScript file that is auto generated by SignalR which contains generated hub proxies for every hub in your SignalR project.
For instance (got this from http://shootr.signalr.net/signalr/hubs) lets take a look at the code snippet.
proxies.h = this.createHubProxy('h');
proxies.h.client = { };
proxies.h.server = {
changeViewport: function (viewportWidth, viewportHeight) {
return proxies.h.invoke.apply(proxies.h, $.merge(["changeViewport"], $.makeArray(arguments)));
},
fire: function () {
return proxies.h.invoke.apply(proxies.h, $.merge(["fire"], $.makeArray(arguments)));
},
...
"this" refers to the hub connection, or rather $.connection.hub. So we're essentially saying proxies.h = $.connection.hub.createHubProxy('h');
Now 'h' is a hub on the server See https://github.com/NTaylorMullen/ShootR/blob/master/ShootR/ShootR/Server/GameHub.cs, more specifically look at the hub name attribute.
Next we have proxies.h.client; this is the endpoint for where users are able to declare their client side functions that will be invoked from the server.
We then have proxies.h.server, this references all the public hub methods on the GameHub.cs. So some of the functions are changeViewport, and fire. This code is auto generated on the server to represent each of your hubs.
Lastly at the end of the signalr/hubs file we extend all of the dynamically created hubs onto the $.connection object so users can then access them via
var myGameHub = $.connection.h;
Hope this helps!
I heard SignalR is a good messaging library. I got some code for SignalR but I am not able to understand how it works.
JS
var hooking;
$(function() {
hooking = $.connection.hooking;
hooking.removeLead = function(ref) {
$("lead" + ref).remove();
};
$.connection.hub.start();
});
C#
// Hooking.cs (placed in application root)
public class Hooking : Hub
{
public void Submit(string jsonString)
{
var serializer = new JavaScriptSerializer();
var json = serializer.Deserialize<HookingLeadResult>(jsonString);
Clients.removeLead(json.Ref); // Remove lead from client hooking windows
// update lead gen
}
}
I have questions about the above code.
What does hooking mean ins $.connection.hooking;
Where is removeLead in hooking.removeLead
What will this do $.connection.hub.start(); ? What does it start? Which method it will invoke at the server side?
Who & how Submit method will be called at the server side? how to pass data from client side to server side. If possible please give me a url for good start for SignalR library.
The Javascript function hooking.removeLead will be invoked whenever you call Clients.removeLead(). All the bindings are done dynamically, between Javascript to C# and between C# and Javascript.
$.connection.hub.start() is actually the connect function. It will connect your client to the server. No messages can be sent or received until you do. The start function allows you to define a callback to be called when it's done connecting.
The Submit method at the server will be called whenever you do a hooking.submit(json) call on your client. For instance, as a result of the user filling in some form and clicking a button.
I recommend starting with the SignalR official wiki: http://www.asp.net/signalr