function not called by nodejs ws-express on connection handler - node.js

I've implemented a websockets api on top of a swagger-express node server.
For websockets I'm using express-ws which utilises the excellent ws library.
However I have come across a problem where the function setInterval is not being called when a websocket client connects.
Confusingly though in the ws.on('connection' function the console.log('websocket connected'); does execute while the setInterval function does not.
Can someone please point out what is wrong with my code?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var expressWs = require('express-ws')(app);
var IndexWS = require('./api/controllers/indexWS');
var config = {
appRoot: __dirname // required config
};
app.ws('/', function(ws, req) {
ws.on('connection', function(conn) {
console.log('websocket connected');
setInterval(function timeout() {
console.log('conn');
}, 500);
});
ws.on('close', function() {
console.log('The connection was closed!');
});
ws.on('error', function() {
console.log('websocket error!');
});
ws.on('message', function(msg) {
setTimeout(function timeout() {
ws.send("500 delay");
}, 500);
});
console.log('websocket connected');
});
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 3030;
app.listen(port, '0.0.0.0');
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('server running on port ' + port );
}
});

Related

Node server working only on localhost Lumen

I am making a real-time Lumen API. For that i have used Node.js to create the server.
It works perfectly fine on localhost, but not when published
This is the code for my Node Server.js
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var Redis = require('ioredis');
var redis = new Redis();
app.listen(6001, function() {
console.log('Server chalu hua');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
console.log('Lijiye Nya connection bna diya gya');
});
io.on('disconnect', function(socket) {
console.log('Connection Dropped');
});
redis.psubscribe('*', function(err, count) {
//
});
redis.on('pmessage', function(subscribed, channel, message) {
console.log(channel);
message = JSON.parse(message);
console.log(message);
io.emit(channel, message.data);
})
Can someone tell what to do, to make it work in Production

how to attach socket.io to SwaggerExpress

I am using swaggerexpress middleware and swagger.
I can't get to work with socket.io
What is the proper way to attach socket.io to my server created?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
var io = require('./api/helpers/socketio');
module.exports = app;
var config = {
appRoot: __dirname
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
swaggerExpress.register(app);
app.listen(10010, function () {
console.log('Application is start listening on localhost:10010');
});
io.on('connection',function(socket){
console.log("A user is connected: " + socket.id);
io.emit('message', "Welcome")
});
});
io.attach(app);
With that approach, my server is not getting up, got an error on socket.io attaching to app.
If you're okay using a different port for socket.io, you could do something like this:
var io = require('socket.io')(10011);
// Or maybe in your case:
// var io = require('./api/helpers/socketio')(10011);
io.on('connection', function(socket) {
console.log('user connected');
});
On the client you'd connect to it like this:
var socket = io('http://localhost:10011');
socket.on('connect', function() {
console.log('Socket connection established');
});

Unable to connect with redis in app.get method

I am trying to learn use case of redis. As each tutorial is suggesting that it is better for caching a data.
I have made a simple demo where I am trying to connect with redis server in a web service get method.
var redis = require('redis');
var client = redis.createClient();
var express = require('express')
var app = express()
var port = process.env.PORT || 8080; // <== this is must
app.get('/fetch_offers', function (req, res) {
client.on('connect', function() {
console.log('connected');
});
});
app.listen(port, function () {
console.log(port)
})
I am trying to access it on localhost machine like http://localhost:8080/fetch_offers
I debugged it using console.log method but it does not print connected message. When I make this method outside the app.get... then it prints on executing node app.js.
I want it should make a redis connection on hitting a URL. I am not sure what is best way ? Can anyone help me ?
var redis = require('redis');
var client = redis.createClient();
var express = require('express')
var app = express()
var port = process.env.PORT || 8080; // <== this is must
client.on('connect', function() {
console.log('connected');
});
app.get('/fetch_offers', function (req, res) {
});
app.listen(port, function () {
console.log(port)
})
What wrong I am doing here ?
It doesn't print connection message because the event fires well before you hit the endpoint - at which point nothing is listening for it and it gets lost. Try something like this:
var redis = require('redis');
var client = redis.createClient();
client.on('connect', () => {
console.log('Redis connected');
});
client.on('ready', () => {
console.log('Redis ready');
});
client.on('error', (err) => {
console.log('Redis error:', err.message);
});
and then in your route handler you can use ping to see if you're connected:
app.get('/fetch_offers', function (req, res) {
client.ping((err, data) => {
if (err) {
console.log('Ping error:', err);
return;
}
console.log('Ping response:', data);
});
});
It would be slightly easier if you use promise-redis and async/await:
app.get('/fetch_offers', async (req, res) => {
try {
console.log('Ping response:', await client.ping());
} catch (err) {
console.log('Ping error:', err);
}
});

Unable to redirect to a url using http node proxy

I am deploying my node.js chat server on the server.Now on server the Https is enabled on port 8443 and my server runs on port 3000.Now whenever i deploy my node.js express server on the server it starts listening but whenever i try to open the page in my browser "Segmentation Fault" is written on my dedicated Server console.I have double checked my certificates they are fine Can anyone guide me here that what would be the thing causing the issue? is that a port related issue or its a code related issue?
// Setup basic express server
var express = require('express');
var app = express();
var fs = require('fs');
var httpProxy=require('http-proxy');
var proxy = httpProxy.createProxyServer({});
var options = {
key: fs.readFileSync('/etc/pki/tls/private/demo.iproctoring.com.key'),
cert: fs.readFileSync('/etc/pki/tls/certs/demo.iproctoring.com.cer')
};
var server = require('https').createServer(options,app,function(req,res)
{
proxy.web(req, res, { target: 'https://demo.iproctoring.com:8443' });
});
var io = require('../..')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
app.use(express.static(__dirname + '/public'));
var numUsers = 0;
io.on('connection', function (socket) {
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
if (addedUser) {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});

Socket.io doesn't emit from an app? (ionic)

I use node.js as server and my ip is example.com:4000. So my endpoint of socket on server side should be example.com:4000. I manage to get it work even when I try to emit something from localhost to example.com:4000.
But when I have an app (I'm using ionic with a real device) but the socket seems didn't send it out the emit of socket.io. I wonder why, it has been 2 days I try to debug this issue.
my code on server side
var server = require("http").Server(express);
var io = require("socket.io")(server);
server.listen(400);
io.on('connection', function(client) {
client.on('msg', function(data) {
console.log(data)
});
});
client side
//angular service
.factory('socket',function(socketFactory){
var myIoSocket = io.connect('http://example.com:4000');
mySocket = socketFactory({
ioSocket: myIoSocket
});
return mySocket;
});
//within my controller
socket.emit('msg',data);
To summarize, things worked on localhost but not when I try on an app?
Try to run this code, since I know that example is working:
Factory
MyApp.factory('socket', function ($rootScope) {
var socket = io.connect('http://localhost:9000');
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
Controller
MyApp.controller('MainCtrl', function($scope, socket){
$scope.users = [];
socket.emit('connection'); });
...
Server side
"use strict";
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
console.log('connected!');
socket.on('disconnect', function() {
console.log('user disconnected');
});
});
server.listen(9000, function() {
console.log('server up and running at 9000 port');
});

Resources