New to Node.js. Searched lots of answers in SO, but could not find appropriate solution for this issue. I'm using custom memcache server code for node.js for getting data from memcached service (stored using php), added only relevant code below:
var net = require("net");
net.createServer(function(socket) {
socket.setEncoding('utf8');
var cmd = {};
var incoming = '';
socket.addListener('receive', function(data) {
incoming += data;
// in the mid of receiving some data, so we can't
// parse it yet.
if(data.substring(data.length - 2) != '\r\n')
return;
data = incoming;
incoming = '';
var parts = data.split(/ /);
if(parts[0].match(/^(add|set|delete|get|gets)$/i)) {
switch(parts[0]) {
case 'add':
var message = JSON.parse(data.split('\r\n')[1]);
self._add.call(socket, parts[1].replace('\r\n', ''), message);
break;
case 'set':
var message = data.split('\r\n')[1];
try {
message = JSON.parse(message);
} catch(e) {}
var subparts = parts[1].replace('\r\n', '').split('/');
self._set.call(socket, subparts.slice(0, 2), subparts.slice(2).join('/'), message);
break;
case 'delete':
self._delete.call(socket, parts[1].replace('\r\n', ''));
break;
case 'get':
self._get.call(socket, parts[1].replace('\r\n', ''));
break;
case 'gets':
var getsparts = parts.slice(1);
getsparts[getsparts.length - 1] =
getsparts[getsparts.length - 1].replace('\r\n', '');
self._gets.call(socket, getsparts);
break;
}
}
});
}).listen(11211, "localhost");
But whenever i try to start the node server, it says EADDRINUSE, as this is due to the reason that memcached service is already running on port 11211. If i change the port to something else such as (51242) then the error does not show up, but no data is retrieved from memcached.
So is there any way i can connect to memcached service using same port 11211 from this node.js memcache server code..?
I'm new to Node.js, so could not figure out any posible solution. So, how can i fix this issue without using any node.js memcached modules, or am i completely on the wrong path..? As a side note I'm running memcached service and nodejs on windows 7. Please suggest
Update
Instead of
net.createServer(function(socket) {
I changed to following for test
this.start = function() {
var socket = net.createConnection(11211, "127.0.0.1");
console.log('Socket created.');
socket.on('data', function(data) {
console.log('RESPONSE: ' + data);
}).on('connect', function() {
socket.write("GET / HTTP/1.0\r\n\r\n");
}).on('end', function() {
console.log('DONE');
});
}
but on console, it shows Socket Created, and then throws error:: Error connect ECONNREFUSED
This is happening because node should be interacting with memcached, not as a server (which binds the ports and accepts incoming connections), but as a client. Look into net.createConnection instead of net.createServer.