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..??
Related
I have implemented a real time notification using socket.io(https://cdnjs.com/libraries/socket.io) on my local and it is working fine. But when I try to implement it on the live server deployed at AWS domain, the frontend that is establishing socket connection to server got error, websocket is unable to connect on the server throwing error:
websocket connection to
'wss://url_from_aws_server/socket.io/?EIO=4&transport=websocket'
failed?
Front-end Side(notification sender)
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.min.js"></script>
<script>
var socket = io('https://app.url_from_aws_server.com:4492', { transports: ['websocket', 'polling', 'flashsocket'] });
$(document).on("click",'#confirmSlot',function(){
socket.emit("notify_platform", {
"shop": locationName,
"therapist": therapistName,
"date": therapistDate,
"time": therapistTime,
});
}
</script>
Server Side
const express = require('express');
const app = express();
...
const sslOptions = {
key: fs.readFileSync(path.join(__dirname, '../ssl/key.pem')),
cert: fs.readFileSync(path.join(__dirname, '../ssl/cert.pem')),
requestCert: false,
rejectUnauthorized: false,
};
const https = require('https').createServer(sslOptions, app);
const io = require('socket.io')(https, {
cors: {
origin: 'https://app.url_from_aws_server.com:4492',
methods: ['GET', 'POST'],
},
});
...
https.listen(process.env.SSL_PORT, () => {
console.log(
`HTTPS Server started at ${process.env.SSL_PORT}, Database - ${process.env.MONGODB_URI}`
);
io.on('connection', function(socket){
console.log('Auth value:' + socket.id);
socket.on('notify_platform', function(details){
socket.broadcast.emit('notify_platform', details);
})
})
});
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 need to send a message to a websocket server through request POST. The client is not a browser but a Node server.
I'm new to websocket.
When I run the code below.
var WebSocket = require("ws");
const express = require("express");
var app = express();
const client = new WebSocket(process.env.URL);
client.on("error", handleError);
client.onopen = () => {
client.send("Message From Client");
};
function handleError(error) {
console.log(error);
}
app.get("/echo", async function (req, res) {
client.once("connection", function connection(cli) {
cli.send(msg);
res.send("send");
});
});
app.listen(3333, function () {
console.log("Example app listening on port 3333!");
});
It shows the error
Error: write EPROTO 19524:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332:
at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:92:16) {
errno: 'EPROTO',
code: 'EPROTO',
syscall: 'write'
}
I'm not sure how to do it with express, but it should be similar to https. Here is how to do it with https.
Basically it has to be the https server that should listen on certain port and also have certs and keys as option passed to it. Then you would pass the https server to websocket server.
When client connects, it'll connect to https and then upgrade to WSS.
Which means your client application can connect to wss://test.mysite.com:1234.
const https = require('https')
const options = {
cert: fs.readFileSync('/etc/ssl/test.mysite.com/cert.pem'),
key: fs.readFileSync('/etc/ssl/test.mysite.com/privkey.pem'),
ca: fs.readFileSync('/etc/ssl/test.mysite.com/chain.pem')
};
const httpsServer = https.createServer(options);
httpsServer.listen(1234, () => console.log('Https Server running on port 1234'));
var ws = new WebSocket.Server({
server: httpsServer
});
ws.on('connection', socket => {
console.log('Conencted')
});
I have a problem since i activated letsencrypt on my domain and did'nt have problem with http server before.
Here is my app.js code:
var app = require('express')();
var fs = require('fs');
var https = require('https');
var secureServer = https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert'),
ca: fs.readFileSync('server.cacert'),
requestCert: true,
rejectUnauthorized: false
}, app).listen(5221, function() {
console.log("Secure Express server listening on port "+ 5221);
});
var io = require('socket.io')(secureServer);
The Secure Express server listening on port 5221 prints out but nothing more and the codes in:
io.on('connection', function (socket) {
console.log(`Socket ${socket.id} connected.`);
}
Is not working at all.
I've also tested with .pem files, with ca.crt or without that... but nothing changes.
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)