How to use SignalR with cross domain - javascript

I am trying to use SignalR with cross domain but i am getting error message when calling start function. Error message is "Uncaught TypeError: Cannot call method 'start' of undefined "
I am using code
Server side:
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});
}
}
}
Client side code.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="/Scripts/jquery-1.6.4.min.js"></script>
<script src="/Scripts/jquery.signalR-1.1.4.min.js"></script>
</head>
<body>
<div></div>
<script type="text/javascript">
var connection = $.connection.hub.url ='http://localhost:9370/signalr';
connection.hub.start()
.done(function () {
alert('Now connected, connection ID=' + connection.id);
});
</script>
</body>
</html>

There are problems with the initialization and start of your Signalr connection, also declare a proxy to reference the hub. See below example:
<script src="/Scripts/jquery-1.6.4.min.js"></script>
<script src="/Scripts/jquery.signalR-1.1.4.min.js"></script>
<script src="http://localhost:9370/signalr/hubs"></script>
<script type="text/javascript">
$.connection.hub.url ='http://localhost:9370/signalr';
var yourHubProxy = $.connection.YourHubName;
//Do something here with yourHubProxy
$.connection.hub.start().done(function () {
alert('Now connected, connection ID=' + $.connection.hub.id);
});
</script>
Another thing, I'm not sure why you're using different versions of SignalR in your server side and client side. To me you had SignalR 2.x on your server side and SignalR 1.1.4 on your cient side.
Take a look at the following link, it's good an example about SignalR with cross domain.
http://damienbod.wordpress.com/2013/11/01/signalr-messaging-with-console-server-and-client-web-client-wpf-client/

#Lin has already answered the question , but i want to inform one important point related to CROSS DOMAIN connection.
Mostly when you googled this issue , we used to find all examples using localhost for ex: http://localhost:9370
As you're binding to localhost only , so it will not work if you are trying to access from other address like http://dev-domain:9370/signalr/hubs remotely you will get HTTP Error 400 i.e the request hostname is invalid.
In order to bind all addresses on the machine ,we have to use it like this
http://*:8097
If anyone found issue after this , check the firewall please :)

Related

Cant connect to a external server (api) in socket io

Im trying to connect to a only api but is not working, is giving me a error of:
XMLHttpRequest cannot load https://api.sports/socket.io/?api_key=aredasdasdadds&EIO=3&transport=polling&t=LsYSPsv. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 596.
The strange thing is in the error showing a different api url.
My code is:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Web socket</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script type="text/javascript">
// Create SocketIO instance, connect
var socket = new io('https://api.sports.com/soccer-/eu/en/matches/summary.json?api_key=aredasdasdadds');
socket.connect();
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
}
</script>
</body>
</html>
What is your server?
First, ou have to check that the version of socket.io is the same on the client and on the server (I see that on client is 2.0.3).
Secondly, you only need use the domain of your web like this:
var socket = io.connect('ws://https://api.sports.com:8443/', {transports: ['websocket']});
And set the port to listen, usually is 8443 for https.
Regards!

Broadcast to all clients outside of hub class in SignalR

I have an ASP.NET Web API that exposes some REST methods. The client browser authenticates with the API using a Login screen. I would like to broadcast a message (javascript alert) to all clients when another client authenticates with the API. No need for the client to invoke a method on the server, just the server calling a single method on the client to display a Javascript Alert.
My Hub class:
public class MyHub : Hub
{
public void BroadcastMessage(string userName)
{
Clients.All.notify(userName);
}
}
Inside my CustomOAuthProvider classs where user authentication takes place:
if (userAuthenticated)
{
var signalRContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
signalRContext.Clients.All.notify(context.UserName);
}
Here is my index.html file with the relevant scripts:
<script src="scripts/jquery-2.2.2.min.js"></script>
<script src="scripts/jquery.signalR-2.2.0.js"></script>
<script src="http://localhost:49834/signalr/hubs"></script>
<script>
(function ($) {
$(function () {
var hubProxy = $.connection.myHub;
hubProxy.client.notify = function (username) {
alert(username + ' has logged in');
};
$.connection.hub.start();
});
})(jQuery);
</script>
Note that the path to the dynamically generated SignalR Hubs script has localhost:49834. This is the url to my web api. I included this because the client is running in a Node.js http-server and is not part of the ASP.NET Web Api project.
When I run this I get no errors on the console and no alerts. I login with one user then open a separate browser and login with a second user. I am not sure why I am not getting a Javascript Alert with the authenticated username.

SignalR js client seems to be ignoring the url port

I'm trying to put together a simple "Hello World" style application with SignalR. The slightly complicating factor is that the SignalR hubs need to be self-hosted, not in IIS/ASP.NET. I've got the server-side working, so far as I can tell, and it's available on port 8080, but I'm having trouble wiring up the client. The problem I'm bumping up against at the moment is that the SignalR client seems to be ignoring the port on the URL that I specify.
Specifically, I've got this code here:
<head runat="server">
<script type="text/javascript" src="/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/Scripts/json2.min.js"></script>
<script type="text/javascript" src="/Scripts/jquery.signalR-0.5.3.js"></script>
<script type="text/javascript" src="http://<%=Request.Url.Host %>:8080/signalr/hubs"></script>
<title>SignalR Test</title>
</head>
<body>
<script type="text/javascript">
$(function () {
// Wire up the client to the SignalR server on the same host
// as the source of this page, but on port 8080.
$.connection.url = "http://<%=Request.Url.Host %>:8080/signalr";
var roomHub = $.connection.roomHub;
$('#echoButton').click(function () {
roomHub.echo($('#echoButton').val())
.error(function (err) {
alert(err);
});
});
$.connection.hub.start({ transport: 'auto', xdomain: true })
.done(function () {
console.log('Connected.');
})
.fail(function (e) {
console.log('Unable to connect:' + e);
});
});
</script>
The :8080/signalr/hubs script loads successfully, and it looks good, i.e., it has the definition for the roomHub in it, so I know that the server is up and running.
However, when $.connection.hub.start() runs, it seems like it should try to open up a connection for a URL something like http://app.dev.alanta.com:8080/signalr/signalr/negotiate?=1353072553935. Instead, Firebug tells me that it's ignoring the 8080 portion, and is instead trying to negotiate a connection with the URL http://app.dev.alanta.com/signalr/signalr/negotiate?=1353072553935. And of course, that doesn't work - there's no SignalR service listening on port 80, just the regular web server - so it fails with the message, "Unable to connect:SignalR: Error during negotiation request".
I should also note that in the jquery.signalR-0.5.3.js file, the bit of code that parses out the connection does indeed seem to ignore the port:
// Resolve the full url
parser.href = connection.url;
if (!parser.protocol || parser.protocol === ":") {
connection.protocol = window.document.location.protocol;
connection.host = window.document.location.host;
connection.baseUrl = connection.protocol + "//" + connection.host;
}
else {
connection.protocol = parser.protocol;
connection.host = parser.host;
connection.baseUrl = parser.protocol + "//" + parser.host;
}
// Set the websocket protocol
connection.wsProtocol = connection.protocol === "https:" ? "wss://" : "ws://";
Is this a bug? Or have I misunderstood something?
Well, I could swear that I'd tried this and it didn't work, but as I was troubleshooting it some more, I changed the URL assignment from this:
$.connection.url = "http://<%=Request.Url.Host %>:8080/signalr";
To this:
$.connection.hub.url = "http://<%=Request.Url.Host %>:8080/signalr";
And to be sure, this is how it's documented here. I thought that I'd seen it documented the first way somewhere, but I can't find it now. Oh well. Chalk this one up to my not paying enough attention.

MQTT Javascript

i've been searching a long time now but i haven't found anything useful yet.
I'm trying to implement a MQTT-Javascript-Client. With the release of Mosquitto V1.0 there was a javascript/websocket-client on http://mosquitto.org/js/mosquitto-1.0.js released.
But i have no idea how to implement this the right way.
For example: I use the example-server on http://broker.mqttdashboard.com as broker.
When i'm running the following html on my xampp-Server nothing happens and on the broker-side there's no client connected.
I assume that there is something incorrect the way i implemented it. It would be great if someone could help me with this.
<html><head>
<script type="text/JavaScript" src="mosquitto-1.0.js"></script>
<script type="text/JavaScript">
var t = new Mosquitto();
t.connect('ws://broker.mqttdashboard.com:1883/',10);
t.subscribe("mqttdashboard/testtopic", 0);
</script>
</head>
<body></body></html>
I also know about the node.js-thing, but i prefer to use the websocket-way.
Thanks.
The server you are connecting to needs to support websockets. The fact that you are connecting to port 1883 suggests to me that it doesn't! The normal thing here would be connecting to port 80 (web) then being upgraded to a websockets connection which happens to talk mqtt. This typically requires the web server to talk to the mqtt broker and be configured to do so, it's not something that happens automatically.
Try using ws://test.mosquitto.org/ws as your url, it's the only websocket enabled mqtt server I know of at the moment.
The MQTT Dashboard now supports websockets on port 8000. It uses the HiveMQ MQTT broker which supports native websockets as of version 1.4.
Mosquitto.js seems to be deprecated now, so I would strongly suggest to use Eclipse Paho.js as the Javascript MQTT client.
Your code with mosquitto.js would work now when modifying it like this:
<html><head>
<script type="text/JavaScript" src="mosquitto-1.0.js"></script>
<script type="text/JavaScript">
var t = new Mosquitto();
t.connect('ws://broker.mqttdashboard.com:8000/',10);
t.subscribe("mqttdashboard/testtopic", 0);
</script>
</head>
<body></body></html>
Try out broker.hivemq.com:8000 for websockets, it supports ws. it should work
I tried with this and it worked so far
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript">
</script>
<script type="text/javascript">
client = new Paho.MQTT.Client("broker.hivemq.com", 8000, "clientId-" + parseInt(Math.random() * 100, 10));
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
var options = {
onSuccess:onConnect,
onFailure:doFail
}
// connect the client
client.connect(options);
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("my/topic1");
}
function doFail(e){
console.log(e);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
document.write(message.payloadString);
alert("messgaearrived!")
}
</script>
and also give a try on cloudmqtt.com

node.js WebSocket Server

currently i try to create a push server instance for new activities around our database. Of course, you find a lot of information about this topic.
I'm using:
http://static.brandedcode.com/nws-docs/#s6-p1
With the following client implementation:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<title></title>
</head>
<body>
<script type="text/javascript">
(function() {
var webSocket = new io.Socket('ws//test', {
port: 8080
});
webSocket.connect();
webSocket.on('connect',function() {
console.log('Client has connected to the server!');
});
webSocket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
webSocket.on('disconnect',function() {
console.log('The client has disconnected!');
});
window.ws = webSocket;
}());
</script>
</body>
</html>
The console returns:
Unexpected response code: 404
XMLHttpRequest cannot load http://ws//test:8080/socket.io/xhr-polling//1303822796984. Origin http://test is not allowed by Access-Control-Allow-Origin.
1303822796984GET http://ws//test:8080/socket.io/xhr-polling//1303822796984 undefined (undefined)
I don't know the problem.
Thanks for your help.
Greets!
You´re trying to connect directly to a WebSocket server using Socket.io.
If you are running only a WebSocket server and not the Socket.io server, the you can use the normal HTML5 API to connect to websockets.
for example:
var ws = new WebSocket("ws://domain:port");
ws.onopen = function(){}
ws.onmessage = function(m){}
ws.onclose = function(){}
What browser are you using?
WebSockets are currently only supported by Google Chrome. Tests in other browsers will fail.
You probably wanted 'ws://push.xxx.binder.test' instead of 'ws//push.xxx.binder.test' (missing colon).
change
var webSocket = new io.Socket('ws//push.xxx.binder.test', {
to
var webSocket = new io.Socket('push.xxx.binder.test', {
You no need to add prefix for your domain for socket.io (especially without colon before slashes). Also var webSocket isn't good naming - socket.io can use not only websockets (even in your errors it using xhr-poliing)

Categories

Resources