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
Related
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 ?
I'm building a websocket chat service, running on NodeJS. It's already working on terminal, if you want to try, check the terminal client package. https://www.npmjs.com/package/#redstone-solutions/hackerchat-client
It works fine on the terminal, now i'm developing a package to integrate web apps (javascript, react, etc), but i can't connect to the websocket via browser.
Basically, that's the backend on the websocket creation:
(I'm not using socket.io, the only dependency is uuid)
async initialize(eventEmitter: NodeJS.EventEmitter): Promise<http.Server> {
const server = http.createServer((request: http.IncomingMessage, response: http.ServerResponse) => {
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Request-Method', '*');
response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
response.setHeader('Access-Control-Allow-Headers', '*');
response.writeHead(200, { 'Content-Type': 'text/plain' })
response.end('Hacker chat server is running!\n\nPlease connect with websocket protocol.')
})
server.on('upgrade', (request, socket) => {
socket.id = uuid()
const headers = [
'HTTP/1.1 101 Web Socket Protocol Handshake',
'Upgrade: WebSocket',
'Connection: Upgrade',
''
]
.map(line => line.concat('\r\n'))
.join('')
socket.write(headers)
eventEmitter.emit(EventTypes.event.NEW_USER_CONNECTED, socket)
})
return new Promise((resolve, reject) => {
server.on('error', reject)
server.listen(this.port, () => resolve(server))
})
}
Here's my try on a new react app, i'm using the same ways that i use on the terminal client.
function App() {
useEffect(() => {
async function run() {
const componentEmitter = new Events()
const connection = await createConnection()
console.log(connection)
}
run()
}, [])
async function createConnection() {
const options = {
port: '9898',
host: 'localhost',
headers: {
Connection: 'Upgrade',
Upgrade: 'websocket'
}
}
const request = http.request(options)
request.end()
return new Promise(resolve => {
request.once('upgrade', (response, socket) => resolve(socket))
})
}
return <div />
}
The request never upgrades on the react app! The console.log(connection) is never called.
I'm not sure if i'm using a resource that's not compatible with browsers (http package, for example)...
The applications are very simple/small, if you need the full code:
https://github.com/redstone-solutions/hackerchat-server
https://github.com/redstone-solutions/hackerchat-terminal-client
Any idea?
I found a way to connect with the socket, but I will need to restructure my application.
const server = new WebSocket('ws://localhost:9898')
Using the native WebSocket API from JavaScript, i can stablish a connection.
With the http library, the request never upgrades, i believe that this lib doesn't fully work on the browser.
What I did here is creating a nodejs server, then whatever I receive a message I send it back to all the clients.
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const port = 6969;
const server = http.createServer(express);
const wss = new WebSocket.Server({ server })
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);
}
})
})
})
after this I create two pages admin.html and client.html in each one a websocket endpoint
like this
ws = new WebSocket('ws://localhost:6969');
How could I change my code to make it send the messages just to the admin page?
thank u #user3094755 i did what u said and it works
i added ws.send("i am admin")in the admin page
and change the code in the server like this
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
if (data=="i am admin")
ws.isadmin=true;
else ws.isadmin=false;
wss.clients.forEach(function each(client) {
if (client.isadmin=true && client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);}
})
})
})
i do not think that this is the best way to do it so
if anyone have an idea pls do not hestate to share it with me
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.
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.