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

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!

Related

Non Existent Clients Connecting To Socket.io

Im creating a realtime application using socket.io and its been going alright, until i found somthing strange going on when a client connects to the server. The client will connect, and the connection event will properly reflect on the server, but shortly after, a cluster of what i can only describe as "fake clients" start connecting to the server and triggering the connection event a seemingly random number of times. These strange connections that come out of nowhere are causing an increasingly big delay on the servers response to actual clients as more start to join. I created an extreamly basic socket.io boilerplate just to see if the strange bug would persist without all the complexity of my application, and to my suprise it did, and i cant understand why. Any info will be greatly appriciated. Here is my basic server and client setup -
const http = require("http");
const fs = require("fs");
const server = http.createServer();
const io = require("socket.io")(server);
io.on("connection",() => {
console.log("A client has connected!");
});
server.on("request",(req,res) => {
fs.readFile("./index.html",(err,data) => {
if (!err && data) {
res.writeHead(200,{"Content-Type": "text/html"});
res.end(data);
} else {
res.writeHead(500);
res.end();
}
});
});
server.listen(3000,() => {
console.log("Server is active...");
});
note how i am logging that a client connected each time the connection event is triggered. Here is the index.html file and client script -
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.socket.io/3.1.1/socket.io.min.js" integrity=" sha384- gDaozqUvc4HTgo8iZjwth73C6dDDeOJsAgpxBcMpZYztUfjHXpzrpdrHRdVp8ySO " crossorigin="anonymous"></script>
<script type="text/javascript">
const socket = io({autoConnect: false});
socket.connect();
</script>
</head>
<body>
</body>
</html>
Here is the console output i get when i connected a single client to the server. Again, its seemingly random each time.
A client has connected
A client has connected
A client has connected
A client has connected
A client has connected
The first one is genuine, but i have no idea where the rest come from, as they even have a different socket id when i tried to log it out. Any type of feedback is appriciated.

How can i connect a Javascript client to a Python-SocketIO server?

I'm just getting started to Python-SocketIO, i created an example server, it looks like this:
import eventlet
import socketio
sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={
'/': {'content_type': 'text/html', 'filename': 'index.html'}
})
#sio.on('connect')
def connect(sid, environ):
print('connect ', sid)
#sio.on('msg')
def message(sid, data):
print('message ', data)
#sio.on('disconnect')
def disconnect(sid):
print('disconnect ', sid)
if __name__ == '__main__':
eventlet.wsgi.server(eventlet.listen(('', 5000)), app)
Then, i have an HTML file which is running on a Django application, i would like to connect that client to my Python-SocketIO server:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>
socket = io.connect('');
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
socket.on('msg',function(data) {
console.log('Received a message from the server!',data);
});
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function send(message) {
socket.send('msg',message);
};
</script>
The problem is that, on my client side, i keep getting the following errors:
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=N5eSEa2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
localhost:5000/socket.io/?EIO=3&transport=polling&t=N5eSEa2:1 Failed to load resource: net::ERR_FAILED
My Django server is running on http://127.0.0.1:8000/. Can anyone help me find what i'm doing wrong?
Set the CORS header on your server:
sio = socketio.Server(cors_allowed_origins='*')
(Source)

How to use SignalR with cross domain

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 :)

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