Created
November 25, 2018 23:09
-
-
Save Sarverott/241c03061605ee94c02933e7edbfca75 to your computer and use it in GitHub Desktop.
simple node.js tcp server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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