I am trying to build a small websocket application. I am trying to implement it on a website that already runs on a secure HTTPS protocol thus the websocket has to be on wss to work.
I build the server using the following code:
var express = require('express');
var app = express();
var fs = require('fs');
var key = fs.readFileSync('/etc/apache2/ssl/www.bigriss.com_private_key.key');
var cert = fs.readFileSync( '/etc/apache2/ssl/www.bigriss.com_ssl_certificate.crt' );
var ca = fs.readFileSync( '/etc/apache2/ssl/bigriss.com_ssl_certificate_INTERMEDIATE.crt' );
var options = {
key: key,
cert: cert,
ca: ca
};
var https = require('https').createServer(options, app);
var io = require('socket.io')(https);
var port = process.env.PORT || 8080;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
var token = socket.handshake.query.token;
io.emit('chat message', msg + token);
});
});
https.listen(port, function () {
console.log('listening on *:' + port);
});
Which would seem to me to be a quite simple and standard implementation. I can access the url https://example.com:8080 properly and it is giving the contents that are read at index.html. On this html file is where I try to establish a connection using:
var socket = io.connect('https://bigriss.com:8080/?token=abc', {
transports: ['websocket'],
upgrade: false,
secure: true,
reconnect: true,
rejectUnauthorized : false
});
Having played several times with the options. Regardless, I get an error in the Chrome Console as being:
failed: Connection closed before receiving a handshake response
failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
In the terminal I get the following node error:
nodejs: ../src/util-inl.h:196: TypeName* node::Unwrap(v8::Local<v8::Object>) [with TypeName = node::TLSWrap]: Assertion `(object->InternalFieldCount()) > (0)' failed.
Aborted
I have testing this same setup with HTTP and it works correctly. Is there anything in particular that I am missing with HTTPS?
Related
I'm trying to do accessing remote redis serverinto local server using node js, but it not showing any error or any success messages on logs with this code, I don't know what happening with this code, Can any one please help me to resolve it. Great Thank you in advance.
Getting this error while running the server
Redis error: Error: Redis connection to 34.214.160.143:6379 failed - connect ETIMEDOUT 34.214.160.143:6379
This is code im trying to access redis remote server database.
This is my app.js file
var express = require('express');
var app = express();
var partials = require('express-partials');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
var redis = require('redis');
var config = require('./config');
app.set('view engine', 'ejs');
app.set('view options', { defaultLayout: 'layout' });
app.use(partials());
app.use(express.static(__dirname + '/static'));
app.use(cookieParser(config.secret));
console.log(config.redisConf);
var redisClient = redis.createClient(config.redisConf);
redisClient.on('connect', function (err) {
console.log('hiiiiiiiiiiiiiiiiiii11111111111111111');
if (err) {
console.log("Error " + err);
} else {
console.log('connected to redis!!');
}
});
redisClient.on("error", function (err) {
console.log('hiiiiiiiiiiiiiiii222222222222222222');
if (err) {
console.log("Error " + err);
}
});
redisClient.set('framework', 'AngularJS', function (err, reply) {
if (err) {
console.log('terrror -- ' + err);
} else {
console.log('the framwork var was SET to AngularJS : the following is the server answer : ');
console.log(reply);
}
});
redisClient.get('framework', function (err, reply) {
if (err) {
console.log('terrror -- ' + err);
} else {
console.log('result' + reply);
}
});
app.use(session({
secret: config.secret,
resave: false,
saveUninitialized: true,
store: new RedisStore({ client: redisClient })
}));
// right after the session
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(config.port);
console.log("App server running on port " + config.port);
and this is config.js file
var config = {
port: 3000,
secret: 'secret',
redisConf: {
host: '34.214.160.143', // The redis's server ip
port: '6379',
pass : 'foobared'
}
};
module.exports = config;
But its not showing any results or error messages on logs
Can any one please help me to resolve this one, Great thank you in advance.
I think you need to check the firewall settings on the server the redis server is located on. I tried to connect to your redis server from my ubuntu using:
redis-cli -h 34.214.160.14 -p 6379 -a foobared
and got:
Could not connect to Redis at 34.214.160.14:6379: Connection timed out
Assuming the redis server is up & running - it might be related to the firewall.
I'm not getting an error but io.on('connection', function(socket){
console.log('a user connected', socket.client.id);
}); doesn't seem to work when I deployed my application in Linode.
But in the development it's working fine.
server.js ( socket io )
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 8002;
io.on('connection', function (socket) {
console.log('a user connected', socket.client.id); // triggering in the development
});
http.listen(port, function () {
console.log('Express server listening on port ' + port);
console.log('env = ' + app.get('env') +
'\n__dirname = ' + __dirname +
'\nprocess.cwd = ' + process.cwd());
});
client html ( note: i change the localhost to my web app ip)
<script src="http://localhost:8002/socket.io/socket.io.js"></script>
and my application seem to be using the socket.io polling-xhr.js
I'm kind of new to this.
I don't know if this will fix your particular problem, but in order to set up socket.io on the same port that your application uses you can configure it this way:
const express = require('express');
const app = express();
const http = require('http');
const hostname = 'localhost';
const port = 80;
// the express app is registered with the server
const server = http.createServer(app);
// setup socket.io and register it with the server
const io = require('socket.io').listen(server);
// tell the application to listen on the port specified
server.listen(port, hostname, function (err) {
if (err) {
throw err;
}
console.log('server listening on: ', hostname, ':', port);
});
Now socket.io runs on the same port as your application.
I'm trying to implementing cluster on nodejs and using Socket.io in my application, after some search and introduced about that and finding sticky-socket-cluster i try to use that, here is sample code which i use the documentetion of library, but login socket not working and dont print log
require('sticky-socket-cluster/replace-console')();
var options = {
workers : require('os').cpus().length, // total workers (default: cpu cores count).
first_port : 8000, // 8000, 8001 are worker's ports (default: 8000).
proxy_port : 3000, // default (5000).
session_hash: function (req, res) {
return req.connection.remoteAddress;
},
no_sockets: false // allow socket.io proxy (default: false).
};
require('sticky-socket-cluster')(options, start);
function start(port) {
var express = require('express');
var http = require('http');
var app = express();
var server = http.Server(app);
var socket = require('socket.io')(server);
socket.on('connection', function (socket) {
console.log("socket.io connection handler...");
});
socket.on('login', function (data) {
console.log(data.username);
});
server.listen(port, function () {
console.log('Express and socket.io listening on port ' + port);
});
}
So I moved app.listen to the top, but now it gives me an error that port is in use. I believe this is because I set up my websocket on this port, but how do I do it then?
var server = require('websocket').server, http = require('http');
var express = require('express');
var app = express();
app.listen(8080);
var socket = new server({
httpServer: http.createServer().listen(8080)
});
socket.on('request', function(request) {
var connection = request.accept(null, request.origin);
app.get('/', function(request, response) {
var id = request.query.steamid;
console.log("STEAMID:",id);
response.send("I have received the ID: " + id);
});
connection.on('message', function(message) {
connection.sendUTF(message);
});
connection.on('close', function(connection) {
console.log('connection closed');
});
});
I believe you need to listen on connection and not on request
socket.on('connection', function(sock) {
sock.on('message', function(message) {
sock.send(message);
});
sock.on('close', function() {
console.log('connection closed');
});
});
put your app.listen(3000); outside of request event.
so,your express server get chance to initialize port to listen.
Currently it is in callback of request event and it will get called once client-server connection of web-socket is established.
As far as URL concern
ws://localhost:8080/?steamid=123456789
you have configured websocket to listen on port 8080.But your express is configured to listen port 3000.So it is not possible to catch request on express Server configured on different port which is requested through web-socket configured on another different port.
url should be like this.
http://localhost:3000/?steamid=123456789
because your express server using http protocol and not websocket
The following code works when deployed locally, receiving a request, and forwarding it to another server to validate a license:
var express = require("express");
var app = express();
var request = require("request");
var ddKey = "someKey";
var ddSecret = "someSecret";
var ProId = "someId";
var testLicense = "someLicense";
app.get("/", function(req, res){
var license = req.query["license"] || "test";
var url = "https://"+ddKey+":"+ddSecret+"#licenseServer.com/products/"+ProId+"/licenses/check_valid?key="+license;
request.get(url, {"auth": {"user": ddKey, "pass": ddSecret}, "json": true}, function(error, response, body){
res.send("BODY:", response.body);
});
});
var port = process.env.PORT || 3001;
app.listen(port, function(){
console.log("listening on port ", port);
});
When I deploy it on heroku however, and send a request to the heroku app I get a "no data received" screen along with this message:
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
When I check the heroku logs I see that heroku is indicating the following error:
Poorly formatted HTTP response
I am unable to locate what constitutes a correctly formatted response.
Thank you for any help you can provide.