Socket io not working over https, how to solve that? - javascript

I run this node script on my server, I can connect via my localhost copy of my webpage. However, I canon't connect from the copy hosted on my server as it's served over HTTPS. I get the error:
Mixed Content: The page at 'https:// ***** .com' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://***** :5000/socket.io/?EIO=3&transport=polling&t=Npij0pe'. This request has been blocked; the content must be served over HTTPS.
socket.io server side code
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', function(socket) {
console.log('Sockete birileri bağlandı');
socket.on('send-message', function(data) {
console.log(data);
io.emit('messages', data);
})
socket.on('disconnect', function() {
console.log('birileri geldi ve gitti')
})
});
server.listen(5000);
client side:
var socket = io('https://*****:5000');
php controller:
$client = new Client(new Version2X('http://*****:5000'));
$client->initialize();
$client->emit('send-message', [
'sender_id' => $currentUser_company_id,
'reciver_id' => $user->company_id,
'messege' => request()->message_text,
'send_time' => date("H:i")
]);
$client->close();
It's working well on localhost, but it's not over https. How can i solve this error ?

Related

can't connect to websocket (Mixed Content)

so i was trying to make web socket server
node js
const WebSocket = require("ws");
var porth = process.env.PORT || 80;
const wss = new WebSocket.Server({port:porth})
wss.on("connection", ws => {
console.log("nowe połączenie");
ws.on("message", data => {
console.log(data.toString());
});
ws.send("hej");
ws.on("close", () =>
{
console.log("rozłączenie");
});
})
app.js
ws.addEventListener("open", () => {
console.log("połączono")
ws.send("test");
ws.addEventListener("message", data => {
console.log(data.data)
})
})
and when i host it on my pc it works but
when i upload it to github pages it keeps
sending me error:
Mixed Content: The page at 'https://*****.github.io/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://****.herokuapp.com/'. This request has been blocked; this endpoint must be available over WSS.
and i dont know what should i do about it
So from this error I assume that you are connecting between secure and not secure site. I'm not sure but if I can I would suggest you to see ws https server. Maybe this will help https://github.com/websockets/ws#external-https-server

socket io not receiving events for both client and server

I followed the socket io website and implement client and server, below is my code
server
const exp = require('express')();
const http = require('http').createServer(exp);
const io = require('socket.io')(http,{
cors : {
origin : '*'
}
});
http.listen(3000, () => {
console.log('listening on *:3000');
setInterval(function(){
io.sockets.emit('hi', 'everyone');
},1000);
io.sockets.on('connection', function (socket) {
socket.on('hello', function (msg) {
console.log(msg);
});
});
});
client
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.4.0/socket.io.js" integrity="sha512-Y8KodDCDqst1e8z0EGKiqEQq3T8NszmgW2HvsC6+tlNw7kxYxHTLl5Iw/gqZj/6qhZdBt+jYyOsybgSAiB9OOA==" crossorigin="anonymous"></script>
<script>
let socket = io('http://localhost:3000',{
transports : ['websocket']
});
socket.on('hi', function(msg) {
console.log(msg);
});
socket.emit('hello','Hello server, im client');
socket.on('connect', function() {
console.log(socket.connected); // true
});
</script>
neither event hi nor hello arrived nor received from and to both client and server, no error whatsoever when running the script and client connecting to server. Any help is greatly appreciated.
Make sure to use matching socket.io versions: On your client you use 2.4.0, so install the same version on your server (npm install socket.io#2.4.0).
In the changelog for 2.4.0 you can see how you have to set cors options:
const io = require('socket.io')(http, { origins: "http://localhost:5000" });
You can't use "*" anymore, use your client domain. In newer versions the interface changed.
If you're not using version 2.4.0, the problem could also be the "*" wildcard.

Websocket connection error: returns 101, but does not upgrade

I am setting up some websockets using ws library. I am struggling to set up authorisation using a handshake. I have added a route to our server to upgrade to a websocket connection like so:
.get(
'/chat',
authorisationFunction,
upgradeConnection,
),
The websocket server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3030 });
This is the upgradeConnection function, which will run if authorisation is successful:
const upgradeConnection = (request, socket, head) => {
return wss.handleUpgrade(request, request.socket, head, function done(ws) {
return wss.emit('connection', ws, request);
});
}
I also have a function that listens to messages:
function webSocketsServer() {
wss.on('connection', (ws, request, client) => {
ws.on('message', message => {
ws.send(message);
});
});
}
A connection gets emitted, and from my server I get this response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: QyVvqadEcI1+ALka6j2pLKBkfNQ=
but then immediately on my client I get the error “WebSocket connection to 'ws://localhost:3000/chat’ failed: Invalid frame header”.
But when I bypass the handshake and connect directly to my websocket server, I can send messages successfully. The error is only on the client and not on the backend. What am I missing?
I am not 100% sure it is the only way but might help so I post it.
Based on this answer I would go for a server that uses the same port for http and websocket connections.
You can achieve it like this:
const { createServer } = require('http')
const ws = require('ws')
const express = require('express')
const app = express()
const server = createServer(app)
app.get('/', (req, res) => {
res.send('I am a normal http server response')
})
const wsServer = new ws.Server({
server,
path: '/websocket-path',
})
wsServer.on('connection', (connection) => {
connection.send('I am a websocket response')
})
server.listen(3030, () => {
console.log(`Server is now running on http://localhost:3030`)
console.log(`Websocket is now running on ws://localhost:3030/<websocket-path>`)
})
So your server listens on port 3030 for normal http requests. If it gets a websocket connection request on path '/websocket-path' it is passed to the the ws connection handler and from there you are good to go.

Lua HTTP request in ROBLOX is giving me a 403, but works on when testing in other places

local httpService = game:GetService("HttpService");
local s = httpService:GetAsync("https://rbxapi.herokuapp.com/api/Users/1");
print(s);
This is a simple GET request that sends to my proxy server, but it continues to give me a 403 error.
HTTP 403 (HTTP/1.1 403 Forbidden)
When testing the URL on other sites like API tester, it works completely fine and passes the test.
The proxy server is hosted on heroku, which this is the code for the server:
const _express = require("express"),
_proxy = require("express-http-proxy"),
_fs = require("fs");
_body_parser = require("body-parser")
var client = _express();
var port = process.env.PORT || 5000;
client.use("/api", _proxy("https://api.roblox.com", {
proxyReqPathResolver: function(req){
return require('url').parse(req.url).path;
},
}));
client.listen(port, (err) =>{
if(err){
console.log(`Error: ${err}`);
return;
} else {
console.log(`Server is now listenin' on port ${port}!`);
}
})
Solved, ROBLOX knows that it originated from a game server, thus rejecting it.

Can't get socket.io and nodejs running with OpenShift

I can't get socket.io running on OpenShift. I googled for some hours now but nothing really helped me. Locally it works fine (with different ports and localhost as host of course).
This is my server.js file:
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ipadr = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var http = require('http').createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end();
}).listen(port,ipadr);
console.log(port+":"+ipadr);
var io = require('socket.io').listen(http),
fs = require('fs'),
request = require('request'),
mysql = require('mysql'),
moment = require('moment'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'xxx',
user: 'xxx',
password: 'xxx',
database: 'xxx',
port: 3306
}),
POLLING_INTERVAL = 1000,
pollingTimer;
io.on('connection', function(socket){
console.log('a user connected');
});
var updateSockets = function(data) {
// adding the time of the last update
t = new Date();
t = moment().format('H:mm:ss');
console.log('(%s) Connections: %s', t, connectionsArray.length);
// sending new data to all the sockets connected
connectionsArray.forEach(function(tmpSocket) {
tmpSocket.volatile.emit('notification', data);
});
};
console.log('server.js executed\n');
When I run this on SSH OpenShift it just shows the first console.log with my port and ipadress of OpenShift and the last line of my server.js code:
server.js executed
and that's it. So I don't get the "a user connected" message like when I test it locally.
This is how I want to connect in my client-side .js-file:
var socket = io.connect('http://njs-uniqo.rhcloud.com:8080/');
Browser (Chrome) Console outputs:
> ?s=product&id=10:1 XMLHttpRequest cannot load http://xxx.rhcloud.com:8000/socket.io/?EIO=3&transport=polling&t=1430395459829-1.
> No 'Access-Control-Allow-Origin' header is present on the requested
> resource. Origin 'http://localhost' is therefore not allowed access.
> The response had HTTP status code 503.
If I change the port to 8080 on the client-side .js-file I get ERR_CONNECTION_TIMED_OUT:
GET http://xxx.rhcloud.com:8080/socket.io/?EIO=3&transport=polling&t=1430395346761-6 net::ERR_CONNECTION_TIMED_OUT
You need to use port 8000. It's what openshift forces for websockets.
var socket = io.connect('http://yourapp.rhcloud.com:8000/',{'forceNew':true });
Port 8000 is for http and 8443 is for https
Source
You must edit package.json. Add...
"socket.io": "~0.9.16"
...under dependencies. The server then automatically downloads socket.io which is not present by default.

Categories

Resources