Skip to content

Instantly share code, notes, and snippets.

@Sarverott
Last active November 25, 2018 22:11
Show Gist options
  • Save Sarverott/64a93b31137ba72afe60155c0d81ad59 to your computer and use it in GitHub Desktop.
Save Sarverott/64a93b31137ba72afe60155c0d81ad59 to your computer and use it in GitHub Desktop.
simple node.js tcp client module
/*
USAGE:
*/
const tcpClient=require("./tcp-client.js");
var request=new tcpClient("192.168.0.1", 80);
request.setupConnectListener(function(){
console.log('connected to server!');
});
request.setupDataListener(function(data){
console.log(data);
});
request.setupErrorListener(function(e){
console.log(e);
});
request.setupEndListener(function(){
console.log("connection closed!");
});
request.setupSend("HELLO SERVER");
request.open();
/*
Sett Sarverott 2018
module for tcp client
*/
const net = require('net');
module.exports=class TCPclient{
constructor(ip,port){
var funct=function(){null};
this.ip=ip;
this.port=port;
this.client=null;
this.onConnect=funct;
this.onData=funct;
this.onEnd=funct;
this.onError=funct;
this.sendData="";
}
setupSend(data){
this.sendData=data;
}
setupConnectListener(funct){
this.onConnect=funct;
}
setupDataListener(funct){
this.onData=funct;
}
setupEndListener(funct){
this.onEnd=funct;
}
setupErrorListener(funct){
this.onError=funct;
}
open(){
var hook=this;
this.client=net.createConnection({host:this.ip,port:this.port},function(){
hook.onConnect();
hook.client.write(hook.sendData);
});
this.client.on('data',function(data){
hook.onData(data);
hook.client.end();
});
this.client.on('end',function(){
hook.onEnd();
});
this.client.on('error',function(e){
hook.onError(e);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment