What can I do to keep ram at a reasonable level?
Before i start the server I have about 140mb ram free.
After 16 hours i have about 4mb free ram left.
I'm running this on a rackspace cloud with 256mb ram.
var maxMsgs = 50;
var express = require('express'), sio = require('socket.io'), redis = require('redis'), RedisStore = require('socket.io/lib/stores/redis');
var app = express.createServer(), pub = redis.createClient(), sub = redis.createClient(), client = redis.createClient();
app.configure(function () {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.listen(8002, function () {
var addr = app.address();
console.log('app listening on http://' + addr.address + ':' + addr.port);
});
var io = sio.listen(app, {log: false}), nicknames = {}, history = [], user_count = 0, topic = {topic: '', setBy: 'Server'}, ytvid = {vid: '', setBy: 'Server'};
io.enable('browser client minification');
io.enable('browser client etag');
io.enable('browser client gzip');
io.set('store', new RedisStore({redisPub : pub, redisSub : sub, redisClient : client}));
//io.set('resource', 'socket');
io.sockets.on('connection', function(socket) {
socket.on('join', function(cu) {
if(cu.username && cu.username != 'Guest') {
socket.nickname = cu.username;
socket.emit('connected', nicknames, history, topic, ytvid);
nicknames[cu.username] = cu;
socket.broadcast.emit('nicknames', nicknames);
user_count++;
//socket.broadcast.emit('announcement', {msg: socket.nickname + ' connected'});
}
});
socket.on('message', function(msg, cb) {
if(msg.msg && msg.msg != '') {
msg.time = Date.now() / 1000;
history.push(msg);
while(history.length > maxMsgs) history.shift();
cb(true, msg.time);
socket.broadcast.emit('message', msg);
}
});
socket.on('stopic', function(t) {
if(t.topic && t.setBy && t.topic != '') {
topic = t;
io.sockets.emit('topic', t);
} else {
topic = {topic: 'No topic set', setBy: 'Admin'};
io.sockets.emit('topic', topic);
}
});
socket.on('sytvid', function(v) {
if(v.vid && v.setBy && v.vid != '') {
ytvid = v;
io.sockets.emit('ytvid', v);
} else {
ytvid = {vid: false, setBy: 'Admin'};
io.sockets.emit('ytvid', ytvid);
}
});
socket.on('get debug', function() {
socket.emit('debug', {users: nicknames, history: history, user_count: user_count, topic: topic});
});
socket.on('send command', function(c) {
if(c.type == 'empty') history = [];
io.sockets.emit('command', c);
});
socket.on('disconnect', function() {
if(!socket.nickname) return;
if(!nicknames[socket.nickname]) return;
//nicknames[socket.nickname].status = 'offline';
delete nicknames[socket.nickname];
//socket.broadcast.emit('announcement', {msg: socket.nickname + ' disconnected'});
socket.broadcast.emit('nicknames', nicknames);
user_count--;
});
});
function inArray(needle,haystack){for(var key in haystack){if(needle===haystack[key]){return true;}}return false;}
function zeroPad(digits,n){n=n.toString();while(n.length<digits){n='0'+n;}return n;}
function time(time){if(time==null)time=new Date();else if((time instanceof Date)===false)time=new Date(time);return time;}
Looks like problem in socket.on('join') point.
I recommend you to start using
var profiler = require('v8-profiler');
setInterval(function() {
profiler.takeSnapshot('snappy');
},1000);
like described here http://code.google.com/p/v8/wiki/V8Profiler
So you will now where is your leak starts.
Also carefully check allocation and deallocation of each variable, object and scope.
Let me know if you have questions.
Some people think that socket.io leaks memory when using websockets transport. Try to disable it. Something along the lines of:
io.configure('production', function(){
io.enable('browser client etag');
io.set('log level', 1);
io.set('transports', [
, 'htmlfile'
, 'xhr-polling'
, 'jsonp-polling'
]);
});
Also heroku has to say the following
Related
I am writing a Proof Of Concept (for at least 2 months now) that uses Node cluster (workers), Redis and socket.io.
Socket.io is not in use for chat in this instance - just back to front communication. Ajax is not an option.
I am using pub/sub for redis and have that piece working (I think). At least the values returned from pubClient.get('key') are correct.
When I make a request from the front end and do not navigate or reload the page in any way, things work perfectly - I can make 10 requests and 10 responses are received.
Conversely, when I navigate, the same is not true - and I need to deliver the results no matter how much someone navigates on the front end.
It seems there is a disconnect after a reload. In both consoles - Dev Tools and node js, the socket ids are the same. I'm really scratching my head on this one!
Any help out there?
So, for some mainly socket.io code:
CLIENT:
socket = io('https://' + location.hostname + ':4444/', {
transports: ['websocket', 'polling'],
secure: true,
});
socket.on('download', function(data){// after reload, this never hits
console.log('DOWNLOAD '+ data.download);
});
var pkgs = ['y14Vfk617n6j', 'My77gWYmBLxT', 'IYd6dL9UoXkx'];
if(pkgs.length > 0){
for(var i = 0; i < pkgs.length; i++){
socket.emit('get-request', pkgs[i]);
}
}
SERVER:
var cluster = require('cluster');
var express = require('express');
var numCPUs = require('os').cpus().length;
const { setupMaster, setupWorker } = require("#socket.io/sticky");
const { createAdapter, setupPrimary } = require("#socket.io/cluster-adapter");
var app = express();
const https = require('https');
const { Server } = require("socket.io");
const Redis = require("ioredis");
const sock_nodes = [
{port: 6379, host: '192.168.0.41'},
{port: 6380, host: '192.168.0.34'},
{port: 6381, host: '192.168.0.35'},
{port: 6379, host: '192.168.0.34'},
{port: 6380, host: '192.168.0.35'},
{port: 6381, host: '192.168.0.41'}
];
const port = 4444;
const httpServer = https.createServer(options, app);
const io = new Server(httpServer, {maxHttpBufferSize: 10240000});
const pubClient = new Redis.Cluster(sock_nodes, {
redisOptions: {
password: 'my secret!'
}
});
const subClient = pubClient.duplicate(); // I am not actually using this - should I be?
if (cluster.isMaster) {
for (var i = 0; i < numCPUs; i++) {
// Create a worker
cluster.fork();
}
cluster.on("exit", (worker) => {
console.log(`Worker PID ${worker.process.pid} died`);
var w = cluster.fork();
console.log('WORKER %d died (%s). restarting...', worker.process.pid, worker.state);
w.on('message', function(msg){
console.log("Message Received : " , msg);
});
});
} else {
app.use((req, res, next) => {
var reqip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
//~ console.log(reqip, md5(reqip));
var sess = parseCookies(req, 'session_state');
if(!sess){
res.cookie('session_state', md5(reqip));
}
next();
});
app.get('/', (req, res) => {
getSession(req, res, function(sess){
getPub('currSockets', sess, function(err, socket){
res.render("pages/shared/index", {'ns': sess, 'socket': socket});
});
});
});
});
app.get('/start', function(req, res){
getSession(req, res, function(sess){
getPub('currSockets', sess, function(err, socket){
res.render("pages/shared/start", {'ns': sess, 'socket': socket});
});
});
});
io.on('connection', function (socket) {
var currUser = parseCookies(socket.request, 'session_state');
socket.join(currUser);
getPub('currSockets', currUser, function(err, currSockets){
if (currSockets) {
currSockets = JSON.parse(currSockets);
if (currSockets[currUser]) {
if (currSockets[currUser].stream) {
currSockets[currUser].sock = socket.id;
setCurrSockets(currSockets, currUser, null, function(cSocks){
});
}
}
}
});
socket.on('get-request', function(data){ // can be one or many requests
// there is a similar, currently irrelevant, socket.on('new-request') that is left out here
if(data){
getPub('currSockets', currUser, function(err, currSockets){
currSockets = JSON.parse(currSockets);
if(currSockets){
if(currUser){
if(currSockets[currUser]){
if(currSockets[currUser].stream){
var str = Object.keys(currSockets[currUser].stream);
for(var i = 0; i < str.length; i++){
if(str[i] !== 'sock'){
if(!currSockets[currUser].stream[str[i]]){
delete currSockets[currUser].stream[str[i]];
setCurrSockets(currSockets, currUser, null, function(cSocks){
checkCurrSockets(currUser, data, socket);
});
}
}
}
}
}
}
}
});
}
});
});
httpServer.listen(port, () => {
logs(__line__, `Worker ${process.pid} listening on ${port}`);
});
}
function existsPub(key, cb){
return pubClient.exists(key, cb);
}
function setPub(key, val, cb){
if(val === JSON.stringify({})){
return pubClient.get(key, cb);
}
return pubClient.set(key, val, cb);
}
function getPub(key, currUser, cb){
existsPub(key, function(err, reply){
if(reply === 1){
return pubClient.get(key, cb);// always getting an old socket.id
}
});
}
// Here is the piece that doesn't work after reloading the page
function ioEmit (currSock, target, payload) {
io.to(currSock).emit(target, payload); // doesn't work after page reload
}
// end piece where after reload does not work
getPub('currSockets', currUser, function(err, currSockets){
if( currSockets){
currSockets = JSON.parse(currSockets);
ioEmit(currUser, 'download', {'download': currSockets[currUser].stream[data]);
}
});
function parseCookies (req, name) {
var list = {}, rc;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list[name];
}
function getSession(req, res, callback) {
var sess = false;
if(req.headers) {// handle req
var reqip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
if(req.headers.cookie){
sess = req.headers.cookie.split('=')[1].split(';')[0];
} else {
res.cookie('session_state', md5(reqip));
}
return callback(sess);
} else if(req.request) {// handle socket
//~ console.log('req.request.headers.cookie', req.request.headers.cookie.split('=')[1]);
if(req.request.headers.cookie){
sess = req.request.headers.cookie.split('=')[1].split(';')[0];
//~ req.emit('join', sess);
//~ callback({[sess]: {'sock': req.id}});
callback(req.id);
}
} else {
return callback(null);
}
}
function setCurrSockets(currSockets, currUser, data, cb){
if(Object.keys(currSockets[currUser].stream).length > 0){
if(data){
if(ready(currSockets, currUser, data)){
delete currSockets[currUser].stream[data];// it appears that setCurrSockets is getting called too soon
}
}
setPub('currSockets', JSON.stringify(currSockets), function(err){
});
if(typeof cb === 'function'){
setTimeout(() => {
getPub('currSockets', currUser, function(err, cSocks){
cb(cSocks);// updated callback to return cSocks
}, 2000);
});
}
} else {
currSockets[currUser].stream = {};
setPub('currSockets', JSON.stringify(currSockets), function(err){
if(err){
} else {
if(typeof cb === 'function'){
cb(currSockets);// updated callback to return cSocks
}
}
});
}
}
figured this out. The problem was in here:
for(var i = 0; i < str.length; i++){
if(str[i] !== 'sock'){
>>>> if(!currSockets[currUser].stream[str[i]]){ // never true
// delete currSockets[currUser].stream[str[i]];
setCurrSockets(currSockets, currUser, null, function(cSocks){
checkCurrSockets(currUser, data, socket);
});
}
}
}
so I commented the for loop and kept the setCurrSockets part and it works.
Just thought I would share, in case someone else tries to use redis, node cluster and socket.io together. As #jfreind00 said, you should use an authentication system with a randomly gen'd string for storing cookies.
I am using kafka-node to read stream data and pass it to my web app with Web Sockets using NodeJS. This works fine if I able to define the kafka producer server and the topic I am interested in, however for my use case the end users will input the kafka producer server and the topic and my NodeJS backend will be responsible to receive that request and to create the appropriate kafka/websocket connections.
My idea was the following:
Create a rest API to which the web app could send requests to in order to create a new kafka consumer/web socket connection (/registerTopic)
Save the new kafka consumers in a global array when I create a new kafka consumer so that I can later pause or resume the stream with another rest API call (/pauseTopic and /resumeTopic)
I ran into problems trying to move the WebSocket code into /registerTopic...Whenever I do this everything acts very strangely and I suddenly get 1000x messages at once and then 40-50x messages every second even though the kafka producer is only sending 1 message per second. Any ideas on how I can get this working?
const express = require("express");
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var WebSocketServer = require('websocket').server;
var http = require('http');
var https = require('https');
var kafka = require('kafka-node');
var topics = [];
var privateKey = fs.readFileSync('PATH', 'utf8');
var certificate = fs.readFileSync('PATH', 'utf8');
var credentials = { key: privateKey, cert: certificate };
var consumers = new Set();
// This was working without any issues before I tried to make this dynamic!
/* var Consumer = kafka.Consumer,
client = new kafka.KafkaClient('localhost:9092'),
consumer = new Consumer(
client, [{ topic: 'numtest', partition: 0 }], { autoCommit: false }); */
var server = http.createServer(function (request, response) {
console.log(' Request recieved : ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function () {
console.log('Listening on port : 8080');
});
webSocketServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function iSOriginAllowed(origin) {
return true;
}
// This was working without any issues before I tried to make this dynamic!
/* webSocketServer.on('request', function (request) {
if (!iSOriginAllowed(request.origin)) {
request.reject();
console.log(' Connection from : ' + request.origin + ' rejected.');
return;
}
let connection = request.accept('echo-protocol', request.origin);
console.log(' Connection accepted : ' + request.origin);
connection.on('message', function (message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
}
});
consumer.on('message', function (message) {
console.log('msg');
connection.sendUTF(message.value);
});
connection.on('close', function (reasonCode, description) {
console.log('Connection ' + connection.remoteAddress + ' disconnected.');
});
}); */
var httpsServer = http.createServer(credentials, app);
httpsServer.listen(3000, () => {
console.log("Server running on port 3000");
});
app.get("/getTopics", (req, res, next) => {
res.json(topics);
});
app.post("/registerTopic", (req, res) => {
try {
var client = new kafka.KafkaClient(req.body.host);
var Consumer = kafka.Consumer;
consumer = new Consumer(
client, [{ topic: req.body.topic, partition: 0 }], { autoCommit: false });
let consumerExists = false;
for (let c = 0; c < [...consumers].length; c++) {
if ([...consumers][c].topic == req.body.topic && [...consumers][c].sessionId == req.body.sessionId) {
consumerExists = true;
}
}
if (!consumerExists) {
consumers.add({ 'topic': req.body.topic, 'sessionId': req.body.sessionId, 'consumer': consumer });
}
client.loadMetadataForTopics([], function (error, results) {
Object.keys(results[1].metadata).forEach(function (key) {
var value = results[1].metadata[key];
if (!value['0'].topic.includes('__') && !value['0'].topic.includes('offset')) {
topics.push({ 'producer': req.body.host, 'topic': value['0'].topic });
}
});
});
webSocketServer.on('request', function (request) {
if (!iSOriginAllowed(request.origin)) {
request.reject();
console.log(' Connection from : ' + request.origin + ' rejected.');
return;
}
let connection = request.accept('echo-protocol', request.origin);
console.log(' Connection accepted : ' + request.origin);
connection.on('message', function (message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
}
});
consumer.on('message', function (message) {
console.log('msg');
connection.sendUTF(message.value);
});
connection.on('close', function (reasonCode, description) {
console.log('Connection ' + connection.remoteAddress + ' disconnected.');
});
});
res.json("Working");
} catch (error) {
console.error(error);
res.status(400).send('Unable to register new topic')
}
});
app.post("/pauseTopic", (req, res) => {
try {
console.log(req.body);
let filteredConsumer = [...consumers].filter(function (item) {
console.log(req.body.topic, item.sessionId);
if (item.topic == req.body.topic && item.sessionId == req.body.sessionId) {
return c;
}
});
console.log(filteredConsumer);
//filteredConsumer[0].consumer.pause();
res.json("Working");
} catch (error) {
console.error(error);
res.status(400).send('Unable to register new topic')
}
});
app.post("/resumeTopic", (req, res) => {
try {
let filteredConsumer = [...consumers].filter(function (item) {
if (item.topic == req.body.topic && item.sessionId == req.body.sessionId) {
return item;
}
});
filteredConsumer[0].consumer.resume();
res.json("Working");
} catch (error) {
console.error(error);
res.status(400).send('Unable to register new topic')
}
});
I have a web server running using Node.js with express and socket.io It displays real-time temperature information and allows for real-time control of some basic hardware controllers.
Each time I connect to the server from a different client, a new instance of the content is delivered as opposed to delivering the last configured instance or state.
Things work fine when just one client is used, but I need to be able to monitor the temperatures and control status from multiple clients.
How can I make sure that no matter which client accesses the server, they all see the same state of the server?
Server code below:
var app = require('express')();
var http = require('http').createServer(app);
var socketServer = require('socket.io').listen(http);
var fs = require('fs');
var csv_stream = fs.createWriteStream("tempLog.csv");
var time_handler = require('moment');
SerialPort = require("serialport").SerialPort;
var serialPort;
var portName = '/dev/ttyACM0'; //change this to your Arduino port
var sendData = "";
var debug = false;
app.get('/', function(req, res){
res.sendFile(__dirname + '/public/interface.html')
});
socketServer.on('connection', function(socket){
console.log('a user connected');
socket.on('run', function(data){
serialPort.write('Z' + data + 'A');
console.log('write to ard');
console.log('Z' + data + 'A');
});
socket.on('stop', function(data){
serialPort.write('Y' + data + 'B');
console.log('write to ard');
console.log('Y' + data + 'B');
});
socket.on('configure', function(data){
serialPort.write('X' + data + 'C');
console.log('write to ard');
console.log('X' + data + 'C');
});
socket.on('temperatureValues', function(data){
serialPort.write(data);
console.log('write data to ard');
console.log(data);
});
socket.on('timeValues', function(data){
serialPort.write(data);
console.log('write data to ard');
console.log(data);
});
});
serialListener(debug);
function SocketIO_serialemit(sendData){
//console.log(sendData.length);
if(sendData.length >= 14)
{
var s_data = sendData.split(",");
socketServer.emit('temp1',{'temp': s_data[0]});
socketServer.emit('temp2',{'temp': s_data[1]});
socketServer.emit('temp3',{'temp': s_data[2]});
csv_stream.write(time_handler().format('HH:mm:ss') + ',');
csv_stream.write(s_data[0] + ',' + s_data[1] + ',' + s_data[2]);
csv_stream.write('\n');
//csv_stream.end();
}
else{
console.log("Error");
//var s_data = sendData.split(",");
//console.log(s_data[0]);
//console.log(s_data[1]);
//console.log(s_data[2]);
}
}
// Listen to serial port
function serialListener(debug)
{
var receivedData = "";
serialPort = new SerialPort(portName, {
baudrate: 9600,
// defaults for Arduino serial communication
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
serialPort.on("open", function () {
console.log('open serial communication');
// Listens to incoming data
serialPort.on('data', function(data) {
if (data.toString() == "X")
{
console.log("Control Done");
socketServer.emit('Completed',{'key': data.toString()});
}
if (data.toString()[0] == "S")
{
console.log("Stage Done");
socketServer.emit('Stage',{'key': data.toString()[0]});
}
receivedData += data.toString();
//console.log(receivedData);
if (receivedData .indexOf('E') >= 0 && receivedData .indexOf('T') >= 0) {
sendData = receivedData .substring(receivedData .indexOf('T') + 1, receivedData .indexOf('E'));
receivedData = '';
SocketIO_serialemit(sendData);
}
});
});
}
http.listen(3000, function(){
console.log('listening on *:3000')
});
app.use(require('express').static(__dirname + '/public')); //sever static files (css, js, fonts, etc.)
Im having a problem using Socket.io on Internet Explorer.
After some seconds conected i got this error message:
cannot connect to Web Socket server at ws://example.com.br:80/socket.io/... (SecurityError) make sure the server is running and Flash socket policy file is correctly placed.
I have done some researchs about what is a policy file, but any of those could help me.
Any thoughts?
Thanks!
/*** IO ***/
var
options = { retry_max_delay: config.app.redis.retryMaxDelay },
redis = require('redis'),
client = redis.createClient(config.app.redis.port, config.app.redis.host, options),
Connector = require('./lib/Connector'),
Helper = require('./lib/Helper'),
io = require('socket.io').listen(server),
Social = require('./lib/service/Social'),
Terms = require('./lib/service/Terms'),
UserChecker = require('./lib/service/UserChecker'),
users = {};
io.configure(function() {
'use strict';
io.set('browser client gzip' , false);
io.set('browser client minification' , false);
io.set('close timeout' , 60);
io.set('heartbeat interval' , 25);
io.set('heartbeat timeout' , 60);
io.set('log level' , config.socket.logLevel);
});
io.set('transports', [
'websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling'
]);
io.on('connection', function(socket) {
'use strict';
logger.debug('Socket (' + socket.id + ') connected.');
client.incr('chat:connection');
var
connector = new Connector(socket),
social = new Social(config),
terms = new Terms(config),
userChecker = new UserChecker(connector, socket);
function send(response, bind, callback) {
if (bind) {
connector.addEventListeners();
}
if (callback) {
callback(response);
}
}
socket.on('join', function(message, callback) {
var
json = Helper.toJSON(message),
skip = userChecker.shouldSkip(json, config);
if (skip) {
var data = userChecker.skip(users, json);
users = data.users;
return send(data.response, true, callback);
}
social.check(json, function(response, access) {
if (!access) {
return send(response, false, callback);
}
terms.check(json, function(response) {
send(response, true, callback);
});
});
});
socket.on('disconnect', function() {
users = userChecker.disconnect(users);
});
});
module.exports = app;
I have been trying to figure out a way to connect a WiFly from an Arduino to send some accelerometer data to my node.js server. Currently the way that I have it worked out is having three servers:
Http >> This is for clients purposes
Net server >> This is basically for TCP request, this is how my server receives the information from 3. WS websockets >> this takes the data from the Net server and streams it to the client side.
Here is the code:
var http = require('http');
var fs = require('fs');
var path = require('path');
var url = require('url');
var net = require('net');
var sensorData;
var message = {
"data": ''
}
var newValue,
oldValue,
diff;
//Settings
var HTTP_PORT = 9000;
var NET_PORT = 9001;
var WS_PORT = 9002;
//Server
var mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"
};
http.createServer(function (req, res) {
var fileToLoad;
if (req.url == '/') {
fileToLoad = 'index.html';
} else {
fileToLoad = url.parse(req.url).pathname.substr(1);
}
console.log('[HTTP] :: Loading :: ' + 'frontend/' + fileToLoad);
var fileBytes;
var httpStatusCode = 200;
fs.exists('frontend/' + fileToLoad, function (doesItExist) {
if (!doesItExist) {
console.log('[HTTP] :: Error loading :: ' + 'frontend/' + fileToLoad);
httpStatusCode = 404;
}
var fileBytes = fs.readFileSync('frontend/' + fileToLoad);
var mimeType = mimeTypes[path.extname(fileToLoad).split('.')[1]];
res.writeHead(httpStatusCode, {
'Content-type': mimeType
});
res.end(fileBytes);
});
// console.log("[INIT] Server running on HTTP Port");
}).listen(HTTP_PORT);
proxy.on("close", function(){
console.log("Connection has closed");
});
proxy.on("end", function(){
console.log("Connection has ended");
});
var socket;
var clients = [];
var socketObject;
var server = net.createServer(function (socket) {
socketObject = socket;
socket.name = socket.remoteAddress + ":" + socket.remotePort;
clients.push(socket);
console.log(socket);
socket.write("HTTP/1.1 101", function () {
console.log('[CONN] New connection: ' + socket.name + ', total clients: ' + clients.length);
});
socket.setEncoding('utf8');
socket.on('error', function (data) {
console.log(data);
});
socket.on('end', function () {
console.log('[END] Disconnection: ' + socket.name + ', total clients: ' + clients.length);
});
socket.on('data', function (data) {
console.log('[RECV from ' + socket.remoteAddress + "] " + data);
oldValue = newValue;
newValue = data;
diff = Math.abs(newValue) - Math.abs(oldValue);
console.log(Math.abs(newValue) + '-' + Math.abs(oldValue));
message.data = Math.abs(diff);
console.log('[SAVED] ' + message.data);
});
});
server.listen(NET_PORT, function () {
console.log("[INIT] Server running on NET server port", NET_PORT);
});
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({
port: WS_PORT
});
wss.on('connection', function (ws) {
// ws.send(JSON.stringify(message));
setInterval(function () {
updateXData(ws)
}, 500);
});
function updateXData(ws) {
var newMessage = {
"data": ""
}
newMessage.data = message.data
ws.send(JSON.stringify(newMessage));
}
So the question is: Is there a cleaner way to do this just by using ws to handle the data from the WiFly and then sending it to the client?
Thanks in advance!
Not sure whether this will suit you and might be new to you but you could make use of MQTT, there are free brokers available which are very good and its relatively easy to set up and implement with Arduino equipped with WiFly Shield.
http://mqtt.org/
Hope this helps somewhat!