I have a simple Nodejs tcp chat server. The chat server works normally. I tested with telnet in windows. The problem in the when client connected to chat server and then disconnected. Every time when client connected and disconnected ,memory usage of server rising.
This my code:
// Load the TCP Library
net = require('net');
// Keep track of the chat clients
var clients = [];
// Start a TCP Server
net.createServer(function (socket) {
// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort
// Put this new client in the list
clients.push(socket);
// Send a nice welcome message and announce
socket.write("Welcome " + socket.name + "\n");
broadcast(socket.name + " joined the chat\n", socket);
// Handle incoming messages from clients.
socket.on('data', function (data) {
broadcast(socket.name + "> " + data, socket);
});
// Remove the client from the list when it leaves
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " left the chat.\n");
});
socket.on('close', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " closed.\n");
});
socket.on('error', function (error) {
process.stdout.write('Error:' +error.toString());
//clients.splice(clients.indexOf(socket), 1);
//broadcast(socket.name + " closed.\n");
});
// Send a message to all clients
function broadcast(message, sender) {
clients.forEach(function (client) {
// Don't want to send it to sender
if (client === sender) return;
client.write(message, function(err){
//if(err)
// process.stdout.write('Error', err)
});
});
// Log it to the server output too
process.stdout.write(message)
}
}).listen(5000);