The TCP server is similar to Http server
var net = require( 'net' );
//create a TCP server
var chatServer = net.createServer();
chatServer.on( 'connection', function(client){
//send message to client
client.write('Hi!\n');
client.write('Bye!\n');
client.end();
});
chatServer.listen(9000);
Telnet can be used to test the server
In Windows use Telnet to connect to 127.0.0.1 port 9000 to see the Hi! Bye message
whenever the connection event happens, the function is called.
A more defensive TCP server used for chat room communication
var net = require('net');
var chatServer = net.createServer()
var clientList = []
chatServer.on('connection', function(client) {
client.name=client.remoteAddress + ':' + client.remotePort
client.write( 'Hi' + client.name + '!\n');
console.log( client.name + ' joined')
clientList.push(client);
client.on('data', function(data) {
broadcast(data, client);
});
client.on( 'end', function(){
console.log( client.name + ' quit')
clientList.splice( clientList.indexOf(client), 1)
})
client.on( 'error', function(e){
console.log(e)
})
});
function broadcast(message,client){
var cleanup = []
for(var i = 0; i < clientList.length; i+=1){
if( client !== clientList[i]){
if(clientList[i].writable){
if( message && message != "\n" && message !="\r\n" ){
clientList[i].write(client.name + " says " + message + "\n")
}
}else{
cleanup.push( clientList[i])
clientList[i].destroy()
}
}
}
for( i=0; i < cleanup.length; i+=1 ){
clientList.splice( clientList.indexof(cleanup[i]), 1)
}
}
chatServer.listen(9000);
This program works terrible in windows, javascript has to check "\n" "\r\n" for new line. Putty also works terrible on receiving message. Use linux should be better.