Error during WebSocket handshake: Unexpected response code: 502

websocket
#1

I am making a small websocket-based database on Glitch. My testing was working perfectly at first, but when I ran my test and the client reloaded, I received the error message shown above. I tried turning new parts of the code into comments to fix this, but it seems to be a permanent issue. Here is my code:
On the server:`const WebSocket = require(‘ws’);

const wss = new WebSocket.Server({ port: 8080 });
var fs = require(‘fs’);
var data = ;
var i;

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

function readWriteSync(val) {
var dat = fs.readFileSync(‘stuff.txt’, ‘utf-8’);
var newValue = dat+=val+’ ';
fs.writeFileSync(‘stuff.txt’, newValue, ‘utf-8’);
}

function deleter(){fs.writeFileSync(‘stuff.txt’, ‘’, ‘utf-8’);}
async function reloader(){
fs.writeFileSync(‘reload.txt’, ‘reload’, ‘utf-8’);
await sleep(100);
fs.writeFileSync(‘reload.txt’, ‘’, ‘utf-8’);
}

wss.on(‘connection’, (ws) => {
ws.on(‘message’, (message) => {
console.log(Received message => ${message})
if(message==‘delete’){deleter()}else{
data.push(message);deleter();readWriteSync(message);reloader();}
if(data.length>=10){
for(i=0;i<data.length;i++){
readWriteSync(data[i]);
}
reloader();
}
})
ws.send(fs.readFileSync(‘stuff.txt’, ‘utf-8’));
setInterval(function(){ if(fs.readFileSync(‘reload.txt’, ‘utf-8’)==‘reload’){ws.send(‘reload’)} }, 50);
})On the clienthmspokemondraft
Show
script.js
const url = ‘wss://hmsdraftserver.glitch.me’
const connection = new WebSocket(url)

connection.onopen = () => {
console.log(‘Hi’)
}

connection.onerror = (error) => {
console.log(WebSocket error: ${error})
}

connection.onmessage = (e) => {
console.log(e.data)
if(e.data==‘reload’){document.location.reload()}
}

function send(stuff){
connection.send(stuff)
}

var data;
var v = document.getElementsByTagName(‘input’)[0];
var b = document.getElementsByTagName(‘button’)[0];

function buttonpress(){
data = v.value;
send(data);
}
`

#2

Hi @camelConvention can you provide your project name for someone to take a closer look? Off the top of my head I suspect the issue might be related to the fact that you’re using port 8080 for your websocket port - that port won’t be accessible to anything outside of the project’s container. Only the port related to process.env.PORT will be open outside of the container at any given time, and that will be proxied through ports 80 / 443 externally. That’s consistent with the 502 status code, I believe.

#3

Sorry, I fixed the problem, but I was unable to solve my topic because it was hidden by the spam filter bot. Thanks for your support though!

1 Like