Socket.io - angular.js. - always disconnected with "ping timeout" - angularjs

Trying to connect with Angular js + socket.io to the server (Node.js - nestsJS)
I have both React and Angular app
in react app everything is work
in Angularjs I got always "ping timeout" and then it try to recconect - on the server I saw the connection and it pass the authentication flow.
when I going to the network tab(WS) I got my events after authenticated in the backend so it looks like its a client issue
so every ~30sec the console output disconnect + reason "ping timeout"
Angular code -socket service
.factory('socket', socket);
socket.$inject = ["$rootScope"];
function socket($rootScope) {
const options = {
transports:['websocket'],
// allowUpgrades: false,
query: {
token : "token",
},
forceNew: true
}
var socket = io.connect('/', { ...options, path: `/socket.io` });
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:
socket.on('connect', function (data) {
console.log("connect")
});
socket.on('connection', function (data) {
console.log("connect")
});
socket.on('disconnect', function (data) {
console.log("disconnect")
console.log(data)
});
socket.on('events-test', function (data) {
console.log("test")
console.log(data)
})
in the network tab i can see the "events-test" events and it will create a new "ws" tab evrey reconnection

Solved by change the socket-io client version to 2.3.0
Use socketio version 2 on the client side to match the server. 3 and 4 are incompatible with server v2

Related

Node and Angular socket error in browser console

I am using Node(server) + Angular(client) to implement socket in my application.
Angular bower.json socket components : "angular-socket-io":
"^0.7.0","socket.io-client": "^1.7.2",
Node js socket component in package.json : "socket.io": "^1.7.3",
I am seeing this below web socket error in my chrome browser console :
WebSocket connection to
'wss://ireporter.apple.com/uitracker/socket.io/?EIO=3&transport=websocket&sid=4qBY-qoxEzUQZOvUAACb'
failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
WrappedWebSocket # VM43:161
This error happens probably only in a production environment. Cannot remember seeing this error in when running the application in local.
Also posting ONLY the socket related code from both server and client side :
Node js server-side code
start.js file
var express = require('express');
var configure = require("./config/configure");
var logger = require("./config/components/logger")
var app = express();
var server = require('http').Server(app);
server.listen(process.env.PORT || config.port, function() {
logger.info("Express server listening on port", config.port );
});
//Configure with all the basic middlewares and configs
configure(app,server);
configure.js file
var socket = require('./middleware/socket/socket.js');
module.exports = function (app,server) {
app.use(socket(server));
}
socket.js file
"use strict";
var logger = require("../../components/logger");
module.exports = function(server){
var io = require('socket.io')(server, {path: '/appname/socket.io'});
require('./socketServer.js')(io, logger);
return function (req, res, next) {
req.io = io;
next();
};
};
socketServer.js
//export function for listening to the socket
module.exports = function(io, logger) {
io.on('connection', function(socket) {
socket.on('notification:update', function(data) {
io.emit('notification:update', data);
});
});
};
Angular js Client Side code :
Socket.js
MyApp.factory('Socket', function ($rootScope) {
var socket = io.connect('' , {path: '/appname/socket.io'});
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);
}
});
})
}
};
});
notificationController.js
Socket.on('notification:update', function(data) {
});
-- Could anyone suggest how to resolve the console error?
Turns out there was another reverse proxy in front of your server that I had no control of. Please check your server setings. the problem is not about the code.
Error during WebSocket handshake: net::ERR_CONNECTION_RESET
Also try this one to test your server side.
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.2/socket.io.js"></script>
<script>
/*var socket = io('', {
path: '/appname/socket.io'
});*/
var socket = io.connect('' , {path: '/appname/socket.io'});
socket.on('notification:update', function (message) {
console.log('notification:update ', message);
});
setTimeout(function() {
console.log('emit demo');
socket.emit('notification:update', 'DEMO');
}, 1000);
socket.on('connect', function (data) {
console.log('connection');
});
</script>

Pass user messages depending on request response

Introduction
OK, what I have is a app built in Node and Angular. I pass A users email to my backed using a post in Angular, from the backed the order in the backed is:
Get the email
Get API key
Post email and API key to API
I do this by posting email to backed then using node and express get email use promise resolve (first function) to pass the email to my third function as well as the API key retrieved from the second function.
What I need
Angular post to back end Node
Run first function, If first function has retrieved the email then run function 2. if not correct then pass information to the first post (Angular) to display message.
Run second function, if true run function 3
Finally run post with data collected from function 1 and 2, if post correctly pass 200 code to first function or pass to angular post.
Needed
Verification on the front end (Angular) on each step (function 1, 2 and 3 in Node) they can be response code so that I may print a different message depending on response code
Objective
A user post email on front end, then depending on if the email was accepted on the API let the user know, This is where different messages or redirects come in to play depending if it was a wrong or right email.
My Code
Angular side
This is where the first post to the Node back end happens, would be nice if this could get different response request depending on the results on the back-end.
var firstFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
app.post('/back-end/controller', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
};
Node side (all in controler.js)
First function
I would like this to trigger function 2 if success if not send a response code back to the Angular request.
var firstFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
app.post('/back-end/controller', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
//Promise.all([firstFunction(), secondFunction()]) .then(thirdFunction);
//res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
};
Second function
This function gets API key, if This function is successful trigger function three.
var secondFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Authentication successful !", api_key);
resolve({data_api: api_key});
}
});
console.error("Second done");
}, 2000);
});
};
Third Function
If second function passes then this function should run using the email from the first and the API key from the second, If success then pass pass success back to first function to pass give 200 success to the angular side, or directly send a request response to Angular, If fail then again let the front end know.
function thirdFunction(result) {
return new Promise(function () {
setTimeout(function () {
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
// Configure the request
var api = result[1].data_api;
var login_email = result[0].data_login_email;
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login_email,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
// Start the request
rp(options)
.then(function (parsedBody) {
console.info(login_email, "Is a user, login pass!");
// router.redirect('/login'); // main page url
// res.send.status(200);
})
.catch(function (err) {
console.error("fail no such user");
// res.status(400).send()
});
console.error("Third done");
}, 3000);
}
);
}
Promise.all([firstFunction(), secondFunction()]) .then(thirdFunction);
If anyone knows how to do this please can you help, this is the last part of my app i need to get working, Thanks.
Summery
In summery I would like different response codes Angular side depending on where and when the function got to on backed or if it passed all three functions.
Eg:
request code for fails to post to backed
Fails to get API key on function 2
Fails to send email to API on third function
Email not present on API
Email present on API and all pass, Your In !!
UPDATE
I found I can pass a message back to my Angular post using the following, but how can I make this message different depending on what function has run ?
var firstFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
app.post('/back-end/controller', function (req, res) {
console.log(req.body);
// res.status(500).send({ error: "boo:(" });
res.send('hello world');
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
console.error("First done");
}, 2000);
});
};
I solved this by merging 2 function into one (the retrieve function and post) then i changed the promise chain
var firstFunction = function () {
return new Promise(function (resolve) {
setTimeout(function () {
nodePardot.PardotAPI({
userKey: userkey,
email: emailAdmin,
password: password,
DEBUG: false
}, function (err, client) {
if (err) {
// Authentication failed
console.error("Authentication Failed", err);
} else {
// Authentication successful
var api_key = client.apiKey;
console.log("Success your API key is", api_key);
resolve({data_api: api_key});
}
});
}, 2000);
});
};
var secondFunction = function (result) {
return new Promise(function () {
setTimeout(function () {
app.post('/back-end/controller', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
var api = result[0].data_api;
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
};
var options = {
url: 'https://pi.pardot.com/api/prospect/version/4/do/read',
method: 'POST',
headers: headers,
form: {
'email': login,
'user_key': userkey,
'api_key': api
},
json: true // Automatically stringifies the body to JSON
};
if (login.length !== 0) { // maybe use node email validation ?
console.log("Email Accepted, Next posting to API.......");
rp(options)
.then(function (parsedBody) {
console.info(login, "Is a user, login pass!");
res.status(200).send({ user: login });
})
.catch(function (err) {
console.error("fail no such user");
res.status(400).send('fail to login');
});
} else {
console.log("Failed to get email from front end");
res.status(404).send('Incorrect length');
}
});
});
});
};
Promise.all([firstFunction()]).then(secondFunction);

IONIC not receiving Socket data from server

I am using ionic framework for my android app and MEANJS on my server. I am using Web Sockets to get realtime data. While the server side web application updates automatically every time a CRUD happens in the android application, the android app does not update automatically when a change is made on the server side.
Android App Service(AngularJS)
.service('Socket', ['Authentication', '$state', '$timeout',
function (Authentication, $state, $timeout) {
// Connect to Socket.io server
this.connect = function () {
// Connect only when authenticated
if (Authentication.user) {
this.socket = io('https://cryptic-savannah-60962.herokuapp.com');
}
};
this.connect();
// Wrap the Socket.io 'on' method
this.on = function (eventName, callback) {
if (this.socket) {
this.socket.on(eventName, function (data) {
$timeout(function () {
callback(data);
});
});
}
};
// Wrap the Socket.io 'emit' method
this.emit = function (eventName, data) {
if (this.socket) {
this.socket.emit(eventName, data);
}
};
// Wrap the Socket.io 'removeListener' method
this.removeListener = function (eventName) {
if (this.socket) {
this.socket.removeListener(eventName);
}
};
}
Client Side Controller
if (!Socket.socket && Authentication.user) {
Socket.connect();
}
Socket.on('orderCreateError', function (response) {
$scope.error = response.message;
});
Socket.on('orderCreateSuccess', function (response) {
if ($scope.orders) {
$scope.orders.unshift(response.data);
}
});
Socket.on('orderUpdateSuccess', function (response) {
if ($scope.orders) {
// not the most elegant way to reload the data, but hey :)
$scope.orders = Orders.query();
}
});
Server Controller(NodeJS)
socket.on('orderUpdate', function (data) {
var user = socket.request.user;
// Find the Order to update
Order.findById(data._id).populate('user', 'displayName').exec(function (err, order) {
if (err) {
// Emit an error response event
io.sockets.emit('orderUpdateError', { data: data, message: errorHandler.getErrorMessage(err) });
} else if (!order) {
// Emit an error response event
io.sockets.emit('orderUpdateError', { data: data, message: 'No order with that identifier has been found' });
} else {
order.name = data.name;
order.phone = data.phone;
order.water = data.water;
order.waiter = data.waiter;
order.napkin = data.napkin;
order.complete = data.complete;
order.rating = data.rating;
order.payment_mode = data.payment_mode;
order.order_source = data.order_source;
order.orderfood = data.orderfood;
order.save(function (err) {
if (err) {
// Emit an error response event
io.sockets.emit('orderUpdateError', { data: data, message: errorHandler.getErrorMessage(err) });
} else {
// Emit a success response event
io.sockets.emit('orderUpdateSuccess', { data: order, updatedBy: user.displayName, updatedAt: new Date(Date.now()).toLocaleString(), message: 'Updated' });
}
});
}
});
});
You have two emit channels on your server side but neither event is handled on the client side.
Per socket.io docs, you need something like:
socket.on('orderUpdateSuccess', function (data) {
// do something inside the app that will update the view
console.log(data);
Orders.update(data); // assuming you have a service called Orders to keep track of live data -- don't forget [$scope.$apply][2]
});
Using your example code
Socket.on('orderUpdateSuccess', function (response) {
if ($scope.orders) {
$scope.$apply(function() {
// not the most elegant way to reload the data, but hey :)
$scope.orders = Orders.query();
});
}
});

Is it possible to use socket.io between NodeJS and AngularJS

I have two independent applications (frontEnd and BackEnd). The backEnd is in NodeJS using express framework and the FrontEnd is in AngularJS. Is it possible to use socket.io to send a message from the server (NodeJS) to the client (AngularJS)? How I can do that? I've tried with the following code but it is not working:
server code
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.sockets.on('connection', function(socket) {
//This message is not showing
console.log("socket");
socket.volatile.emit('notification', {message: 'push message'});
});
client code
angular.module('pysFormWebApp')
.factory('mySocket', function (socketFactory) {
var mySocket = socketFactory({
prefix: 'foo~',
ioSocket: io.connect('http://localhost:3000/')
});
mySocket.forward('error');
return mySocket;
});
angular.module('formModule')
.controller('typingCtrl', ['$scope', 'mySocket', typingCtrl]);
function typingCtrl ($scope, mySocket) {
mySocket.forward('someEvent', $scope);
$scope.$on('socket:someEvent', function (ev, data) {
$scope.theData = data;
console.log(data);
});
thanks for the help
This is how I set my connection up. I'm not sure if it's the best way, but it definitely works and I haven't had any performance issues to date.
Client Code:
angular.module('whatever').factory('socket', function ($rootScope) {
var socket = io.connect('yourhost');
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);
}
});
})
}
};
});
angular.module('whatever').controller("MainCtrl", MainCtrl);
function MainCtrl($scope, socket) {
socket.on('channelname', function(data) {
console.log("message: " + data.message);
});
}
Server Code:
var Express = require('express');
var app = new Express();
var server = Http.createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.emit("channelname", {
message: "messagecontent"
});
});

Socket io socket won't carry jwt token in angular factory

I am trying socket.io authorization with jwt in my MEAN stack project. I have problem about socket object won't carry jwt token after I log out and relog in.
when I log in , token will store in local storage
UsersSvc.login($scope.user).success(function(data){
if (data.success) {
store.set('jwt', data.token);
}
then angular socket factory will retrieve jwt from local storage and send to server
.factory('SocketSvc',[ 'store',
function (store) {
this.initSocket = function(){
return io.connect('http://localhost:3000',{ query : 'token=' + store.get('jwt')});
};
var socket = this.initSocket();
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);
}
});
})
},
};
however; after I logged out
$scope.logout = function(){
var account = UsersSvc.currentAccount();
SocketSvc.emit('logout', { account : account});
$state.go('anon.login');
};
then jwt toke will be remove from local storage
if (toState.name == "anon.login") {
store.remove('jwt');
when I log in agin, token in socket query is gone while you logged in successfully. I am dealing with this problems several days. I don't know what happened.
The only way let server get token again is that refresh the page agin manually.
or close the tab and open a new page then log in agin.
My assumption is the problem of angular factory since it is singleton that it's can't be modified.
I don't know it is right or wrong or how to solve the problem. If you have any suggestion. please let me know
I solved this by wrapping the initSocket code into a function in the return block
you are right in pointing that token is null as the user is not logged in.
this.initSocket = function(){
return io.connect('http://localhost:3000',{ query : 'token=' + store.get('jwt')});
};
var socket = this.initSocket();
the above should go inside return block and called once in any Controller for initializing the socket with a valid token
My soultion:
angular.module('mean1App')
.factory('socket', function(socketFactory, $rootScope, Auth) {
var socket = null;
return {
socket: socket,
init: function(){
var ioSocket = io.connect('http://localhost:9000', {
// Send auth token on connection, you will need to DI the Auth service above
'query': 'token=' + Auth.getToken(),
path: '/socket.io-client'
});
socket = socketFactory({
ioSocket: ioSocket
});
},
...
...blah
});

Resources