So I have been searching for a solution for over 4 hours. I'm currently at the end of my resources.
Some background:
I have been trying to implement a socket.io solution for a WebSocket server - I like the extra functionality from this stack. However, I ran a ws server before, and didn't have any issue connecting to it.
I tried connecting to the server by using Postman, and my url that I want to connect to is ws://localhost:3001 and this is the error I'm receiving:
Error: socket hang up
Handshake Details
Request URL: http://localhost:3001/
Request Method: GET
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: cShC021nW+/sgNEMisMOaw==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: localhost:3001
Here is my code that I am running on my local server for testing purposes for socket.io:
const express = require('express');
const socketIO = require('socket.io');
const port = process.env.PORT || 3001;
let app = express();
let server = http.createServer(app);
let io = socketIO(server);
io.on('connection', (socket) => {
console.log('A new user just connected');
});
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
Here is my code for ws that is working fine:
const app = express();
const server = require('http').createServer(app);
const WebSocket = require('ws');
const { uuid } = require('uuidv4');
const wss = new WebSocket.Server({ server: server });
wss.on('connection', (ws) => {
let initMsg = {
id: uuid(),
msg: 'Welcome to the server, please take your ticket',
};
ws.on('message', (msg) => {
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(msg.toString());
}
});
});
});
server.listen(3002, () => {
console.log('listening on port 3000');
});
Package.json:
"dependencies": {
"express": "^4.17.2",
"moment": "^2.29.1",
"socket.io": "^2.4.1"
}
Thanks in advance... :)
Related
I change from "const socketio = require("socket.io-client");" to "const socketio = require("socket.io");" but it is not working.
the third pic is Back-end and fourth is Front-end. it doesn't say the exact error is but "this.ws =" and "websocket.js:50 WebSocket connection to 'ws://localhost:8080/socket.io/?EIO=4&transport=websocket' failed: " is all.
you can check in https://socket.io/docs/v4/server-initialization/ i think it's:
io.on("connection",()=>{}) // on server side
if that doesn't work you can try to move all socket code before server.listen it would be something like this:
const http = require('http')
const { Server } = require('socket.io')
const app = require('./app')
const server = http.createServer(app)
const io = new Server(server, {
cors: {
origin: 'http://localhost:8080',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
},
})
io.on('connection', (socket) => {
console.log("socket",socket);
}
server.listen(process.env.PORT || 5000, () => {
console.log(`Listening on port ${process.env.PORT || 5000}`)
})
I have a problem with an HTTPS and a WebSocket connection (I use Node.JS as a server).
I have generated SSL certificates with OpenSSL and I imported them to the server with the following code:
const https = require('https');
var app = express();
...
const WebSocket = require('ws');
...
var serverHttps = https.createServer({
key: fs.readFileSync(path.join(pathCertificati, 'key.pem')),
cert: fs.readFileSync(path.join(pathCertificati, 'cert.pem'))
}, app).listen(3000, () => {
console.log('In ascolto sulla porta 3000 HTTPS.')
})
const wss = new WebSocket.Server({
server: serverHttps,
adress: '192.168.12.40',
port: 9000
});
With this code I should have a WebSocket handling an HTTPS connection, correct?
Client side, I have the following code:
socket = new WebSocket("wss://192.168.12.40:9000");
socket.onopen = function ()...
socket.onclose = function ()...
socket.onerror = function (error) {
console.log("Errore nella connessione!");
console.log(error);
}
When I load the page using the address: https://192.168.12.40:3000 and the above code is executed, the error message appears:
WebSocketScript.js:26 WebSocket connection to 'wss://192.168.12.40:9000/' failed: Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR
Do you have any ideas to establish the WebSocket Connection on an HTTPS page?
Thanks a lot.
I have found the solution to the problem. The solution is:
Server-side code:
var serverHttps = https.createServer({
key: fs.readFileSync(path.join(pathCertificati, 'key.pem')),
cert: fs.readFileSync(path.join(pathCertificati, 'cert.pem'))
}, app).listen(3000, () => {
// Messaggio di attivazione del server in ascolto sulla porta 3000
console.log('Listening ' + 3000 + ' HTTPS.');
})
serverHttps.on('upgrade', function upgrade(request, socket, head) {
const pathname = url.parse(request.url).pathname;
if (pathname === "/") {
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request);
});
}
});
// Create WebSocket
const wss = new WebSocket.Server({ noServer: true });
wss.on('error', function () {...}
wss.on('connection', function (ws) {...}
Client side:
socket = new WebSocket("wss://192.168.12.40:3000);
This is the same address used on the server side and it fire the event "serverHttps.on('upgrade'"
Thanks a log...
I wrote a simple node express server for webRTC using peerjs-server and simple client using peerjs. Everything works fine on localhost, but when I try it on vps, I get error:
Firefox can't connect with server ws://my.vps/peerjs/peerjs?key=peerjs&id=hj3hpekwaa38fr00&token=ymtfvhagiw
PeerJS: Socket closed.
PeerJS: ERROR Error: Lost connection to server.
Error: "Lost connection to server."
emitError https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:16426
_initializeServerConnection https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:12260
emit https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:25516
onclose https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js:1:19350
Server:
const express = require('express');
enter code here`const app = express();
const ExpressPeerServer = require('peer').ExpressPeerServer;
app.use(express.static('./public'));
const server = app.listen(80, () => { // 3000 on localhost
console.log('Express server listen on port ' + 80);
});
const options = { debug: true };
const peerserver = ExpressPeerServer(server, options);
app.use('/peerjs', peerserver);
app.use('/*', express.static('./public/index.html'));
Client:
var peer = new Peer('', {
host: location.hostname,
port: location.port || (location.protocol === 'https:' ? 443 : 80),
path: '/peerjs',
debug: 3
});
peer.on('open', function (id) {
console.log(id);
});
Any help appreciate.
It looks like you are connecting with server ws://my.vps/, which is a web socket to a server at http://my.vps/ which doesn't seem to exist.
It should probably also be using https (or wss)
i'm making a game that use WebSockets and this is the code that i use to start a WebSocket server:
const server = require("http").Server(app);
const port = 3005;
server.listen(port, () => {
console.log('Server started on port: ' + port);
});
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ server })
wss.on('connection', function connection(ws) {});
And this code i use for connecting a user to the WebSocket:
this.SERVER_URL ='ws://localhost/?fvukovic'; <-- fvukovic is the user
this.ws = new WebSocket(this.SERVER_URL, ["test"]);
this.ws.onopen = () => {
console.log('open');
};
This works perfectly, but when i push that on server and i change the ip address to 195.201.119.221 which is the ip of the server, port is still 3005, i cant connect to it anymore..
I get this error:
WebSocket connection to 'ws://195.201.119.221:3005/?fvukovic' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT
Do i need something more when i put the the app on a real server?
I have a application in express.js. Am unable to create wss on a HTTPS web server.
var fs = require('fs');
var express = require('express');
var app = express();
var cfg = {
ssl: true,
port: 8001,
ssl_key: 'sslcert/ssl.key',
ssl_cert: 'sslcert/ssl.crt'
};
var httpServ = (cfg.ssl) ? require('https') : require('http');
if (cfg.ssl) {
httpsServer = httpServ.createServer({
key: fs.readFileSync(cfg.ssl_key),
cert: fs.readFileSync(cfg.ssl_cert)
}, app)
.listen(cfg.port, function () {
console.log('Magic happening at https://Secure');
});
} else {
httpsServer = httpServ.createServer(app)
.listen(cfg.port, function () {
console.log('Magic happening at http://InSecure');
});
}
var WebSocketServer = require('websocket')
.server;
var wsServer = new WebSocketServer({
httpServer: httpsServer
});
wsServer.on('connection', function connection(ws) {
console.log('Socket Connected');
});
I'm under the impression that passing a reference of the web server to WebSocket, then WebSocket would know the port and SSL capabilities of the server. But every time I get an error in the console
WebSocket connection to 'ws://localhost:8001/?trackme=TUKOCVPAF' failed: Connection closed before receiving a handshake response
How can I create a wss://localhost:8001/?trackme=TUKOCVPAF' when creating the Websocket..??