Skip to content

Instantly share code, notes, and snippets.

@s4l1h
Created January 16, 2015 01:35
Show Gist options
  • Save s4l1h/d10aad092350cb50a9fc to your computer and use it in GitHub Desktop.
Save s4l1h/d10aad092350cb50a9fc to your computer and use it in GitHub Desktop.
socketPost.js
var net = require('net');
function HttpRequest(host, port, path, method) {
return {
headers: [],
port: 80,
path: "/",
method: "POST",
socket: null,
_setDefaultHeaders: function() {
this.headers.push(this.method + " " + this.path + " HTTP/1.1");
this.headers.push("Host: " + this.host);
},
SetHeaders: function(headers) {
for (var i = 0; i < headers.length; i++) {
this.headers.push(headers[i]);
}
},
WriteHeaders: function() {
if(this.socket) {
this.socket.write(this.headers.join("\r\n"));
this.socket.write("\r\n\r\n"); // to signal headers are complete
}
},
MakeRequest: function(data) {
if(data) {
this.socket.write(data);
}
this.socket.end();
},
SetupRequest: function() {
this.host = host;
if(path) {
this.path = path;
}
if(port) {
this.port = port;
}
if(method) {
this.method = method;
}
this._setDefaultHeaders();
// socket.setKeepAlive(true);
this.socket = net.createConnection(this.port, this.host);
this.socket.setKeepAlive(true);
}
}
};
var request = HttpRequest("www.defter.us");
request.socket.setTimeout(30000, function(){
console.error("Connection timed out.");
});
request.socket.on("data", function(data) {
console.log(data.toString('utf8'));
});
request.SetupRequest();
request.WriteHeaders();
request.MakeRequest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment