I'm using NodeJS to put flag in memcache.
This is code:
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
var memcache = require('memcache');
var client = new memcache.Client();
server.listen(3005);
io.sockets.on('connection', function (socket) {
socket.emit('connected');
socket.on('check',function(data){
client.on('connect', function(){
console.log('connect');
});
client.connect();
client.set(data.id, 1, function(error, result){
console.log('Key added');
console.log(result);
client.get(data.id, function(error, result){
socket.emit('checked',data.id);
});
},600);
});
});
In same time I have about 60 connections.
Some users complain that this code takes about 10-12 seconds to load.
Added socket.disconect() after socket.emit('checked',data.id) but it start to work slower.
Any ideas?
All users use Android / iOS native browsers.
Don't connect to memcached on each call, instead reuse an existing connection:
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
var memcache = require('memcache');
var client = new memcache.Client();
server.listen(3005);
client.on('connect', function() {
console.log('connect');
io.sockets.on('connection', function (socket) {
socket.emit('connected');
socket.on('check',function(data){
client.set(data.id, 1, function(error, result){
console.log('Key added');
console.log(result);
// maybe unnecessary, just check if error is present
client.get(data.id, function(error, result){
socket.emit('checked',data.id);
});
},600);
});
});
});
client.connect();
You call:
client.connect();
but your corresponding connection handler merely logs a message rather than performing the action you wanted to perform.
client.on('connect', function(){
console.log('connect');
});
You have a function:
client.set(data.id, 1, function(error, result){
console.log('Key added');
console.log(result);
client.get(data.id, function(error, result){
socket.emit('checked',data.id);
});
},600);
.. which really should be wrapped inside the client.on("connect") handler so I wonder why your code succeeds at all?
Possibly your first or first few attempts to access memcached fail but then succeed because the client variable is re-used and the connection may stay alive. But - risky.