Skip to content

Instantly share code, notes, and snippets.

@Sarverott
Created November 25, 2018 23:09
Show Gist options
  • Save Sarverott/241c03061605ee94c02933e7edbfca75 to your computer and use it in GitHub Desktop.
Save Sarverott/241c03061605ee94c02933e7edbfca75 to your computer and use it in GitHub Desktop.
simple node.js tcp server
const tcpServer=require("./tcp-server.js");
var server=new tcpServer(80);
server.setupServeListener(function(){
console.log("START SERVER on port "+this.port);
});
server.setupConnectListener(function(conn){
console.log("client connected!!! "+conn.remoteAddress);
});
server.setupDataProcessor(function(data, conn){
console.log(data);
return "HELLO CLIENT";
});
/*
Sett Sarverott 2018
module for tcp server
*/
const net=require("net");
module.exports=class TCPserver{
constructor(port){
this.port=port;
var funct=function(x=null,y=null){null};
this.async=false;
this.onServe=funct;
this.onError=funct;
this.onClientEnd=funct;
this.onData=funct;
this.onConnect=funct;
this.dataProcessor=funct;
}
setAsyncResponse(isAs){
this.async=isAs;
}
setupServeListener(funct){
this.onServe=funct;
}
setupErrorListener(funct){
this.onError=funct;
}
setupClientEndListener(funct){
this.onClientEnd=funct;
}
setupDataListener(funct){
this.onData=funct;
}
setupConnectListener(funct){
this.onConnect=funct;
}
setupDataProcessor(funct){
this.dataProcessor=funct;
}
dataProcessing(connection, data){
if(this.async){
this.dataProcessor(data, connection, function(output){
connection.write(output);
});
}else{
connection.write(this.dataProcessor(data, connection));
}
}
serve(){
var hook=this;
this.server=net.createServer(function(connection){
hook.onConnect(connection);
connection.on('end',this.onClientEnd);
connection.on('data',function(data){
hook.onData(data);
hook.dataProcessing(connection, data);
});
connection.pipe(connection);
});
this.server.on('error',this.onError);
this.server.listen(this.port,this.onServe);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment