Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7510925
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T23:22:51+00:00 2026-05-29T23:22:51+00:00

I’m sending data from client sockets through a proxy server to an http server.

  • 0

I’m sending data from client sockets through a proxy server to an http server. When I post this data from proxy server to http, everything works fine, but if I close the http server, the proxy server dies.

I thought the post.end() function would close the request, but apparently not?! Do I have to do some callback magic?

I’ve attached my console output below, but here’s a brief explanation of the steps:

  1. start server: node –harmony_weakmaps server.js
  2. start api(http server): node api.js
  3. start a client(telnet localhost 5280)
  4. client connect message: {“m”:”connect”,”id”:”123″}
  5. client message to api: {“m”:”x”,”id”:”123″}
  6. kill api process- it blows up

console(server):

>>node --harmony_weakmaps server.js
Starting heartbeat
TCP server listening on 127.0.0.1:5280
HTTP server listening on 127.0.0.1:9002
Connection from 127.0.0.1:49356 id:undefined
received data: {"m":"connect","id":"123"}

id: 123
m: connect
associating uid 123 with socket [object Object]


Heartbeat Time: Tue Feb 14 2012 15:27:08 GMT-0800 (PST)
received data: {"m":"x","id":"123"}

id: 123
m: x
Invalid JSON:{"m":"x","id":"123"}

events.js:48
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: socket hang up
    at createHangUpError (http.js:1104:15)
    at Socket.onend (http.js:1181:27)
    at TCP.onread (net.js:369:26)

console(client, telnet):

>>telnet localhost 5280
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
>>{"m":"connect","id":"123"}
{"m":"connect","id":"123","success":"true"}
{"m":"pulse"}
>>{"m":"x","id":"123"}
{"success":"false","response":"invalid JSON"}
Connection closed by foreign host.

console(api):

>>node api.js 
API (HTTP server) listening on 127.0.0.1:8081
Request received: m=x&id=123&success=true
id: 123
m: x
// Then I close it (^C)

server.js(tcp-ip server that posts data from sockets to an http server):

// Launch Instructions
// node --harmony server.js

var net = require('net'); // tcp-server
var http = require("http"); // http-server

// Map of sockets to devices
var id2socket = new Object;
var socket2id = new WeakMap; // allows us to use object as key to hash

// HTTP:POST outbound function
// http://www.theroamingcoder.com/node/111
function postOut(dataToPost){
    var querystring = require('querystring');
    var http = require('http');

    var post_domain = 'localhost';
    var post_port = 8081;
    var post_path = '/';

    var post_data = querystring.stringify(dataToPost);

    var post_options = {
      host: post_domain,
      port: post_port,
      path: post_path,
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': post_data.length
      }
    };

    var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        console.log('Response: ' + chunk);
      });
    });

    // write parameters to post body
    post_req.write(post_data);
    post_req.end();
    request.on("response", function (response) {
        console.log(response);
    });
}

function removeSocketFromMap(id,socket){
    console.log("removeSocketFromMap socket:"+socket+" id:"+id);
    delete id2socket[id];
    socket2id.delete(socket);
    //TODO: print map???
}

// Setup a tcp server
var server_plug = net.createServer(

    function(socket) {
        // Event handlers
        socket.addListener("connect", function(conn) {
            console.log("Connection from " + socket.remoteAddress + ":" + socket.remotePort + " id:"+socket.id );   
        });

        socket.addListener("data", function(data) {
            console.log("received data: " + data);
            try {
                request = JSON.parse(data);

                response = request;
                if(request.m !== undefined && request['id'] !== undefined){ // hack on 'id', id is js obj property
                    console.log("id: "+request['id']);
                    console.log("m: "+request.m);
                    if(request.m == 'connect'){
                        console.log("associating uid " + request['id'] + " with socket " + socket);
                        id2socket[request['id']] = socket;
                        socket2id.set(socket, request['id']);
                        response.success = 'true';
                    } else {
                        response.success = 'true';

                        postOut(request)
                    }
                }
                socket.write(JSON.stringify(response));
            } catch (SyntaxError) {
                console.log('Invalid JSON:' + data);
                socket.write('{"success":"false","response":"invalid JSON"}');
            }
        });

        socket.on('end', function() {
            id = socket2id.get(socket);
            console.log("socket disconnect by id " + id);
            removeSocketFromMap(id,socket);
        });

        socket.on('timeout', function() {
            console.log('socket timeout');
        });

    }
);

// Setup http server
var server_http = http.createServer(
    // Function to handle http:post requests, need two parts to it
    // http://jnjnjn.com/113/node-js-for-noobs-grabbing-post-content/
    function onRequest(request, response) {
        request.setEncoding("utf8");
        request.content = '';

        request.addListener("data", function(chunk) {
            request.content += chunk;
        });

        request.addListener("end", function() {
            console.log("Request received: "+request.content);

            try {
                var json = JSON.parse(request.content);
                var id = json['id'];
                var m = json['m'];
                console.log("id: "+id);
                console.log("m: "+m);

                // TODO: refactor this into another function
                try {
                    var socket = id2socket[id];
                    socket.write('{"m":"post"}');
                } catch (Error) {
                    console.log("Cannot find socket with id "+id);
                }

            } catch(Error) {
                console.log("JSON parse error: "+Error)
            }
        });
    }
);

// Heartbeat function
console.log("Starting heartbeat");
var beat_period = 20;
setInterval(function() {
    console.log("Heartbeat Time: " + new Date());
    for(var id in id2socket) {
        var socket = id2socket[id];
        try {
            socket.write('{"m":"pulse"}');
        } catch(Error) {
            removeSocketFromMap(id,socket);
        }

    }
}, beat_period * 1000);




// Fire up the servers
var HOST = '127.0.0.1';
var PORT = 5280;
var PORT2 = 9002;

// accept tcp-ip connections
server_plug.listen(PORT, HOST);
console.log("TCP server listening on "+HOST+":"+PORT);

// accept posts
server_http.listen(PORT2);
console.log("HTTP server listening on "+HOST+":"+PORT2);

api.js(http server):

var http = require("http"); // http-server
var querystring = require('querystring');

// Setup http server
var server_http = http.createServer(
    // Function to handle http:post requests, need two parts to it
    // http://jnjnjn.com/113/node-js-for-noobs-grabbing-post-content/
    function onRequest(request, response) {
        request.setEncoding("utf8");
        request.content = '';

        request.addListener("data", function(chunk) {
            request.content += chunk;
        });

        request.addListener("end", function() {
            console.log("Request received: "+request.content);

            try {
                // Parse incoming JSON
                var json = querystring.parse(request.content);
                var id = json['id'];
                var m = json['m'];
                console.log("id: "+id);
                console.log("m: "+m);

            } catch(Error) {
                console.log("JSON parse error: "+Error)
            }
        });
    }
);


// Fire up the servers
var HOST = '127.0.0.1';
var PORT = 8081;

server_http.listen(PORT);
console.log("API (HTTP server) listening on "+HOST+":"+PORT);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T23:22:52+00:00Added an answer on May 29, 2026 at 11:22 pm

    Silly me, I’m not up to speed on proper error handling in node. Fixing postOut() did the trick:

    function postOut(dataToPost){
    
        var querystring = require('querystring');
        var http = require('http');
    
        var post_domain = 'localhost';
        var post_port = 8081;
        var post_path = '/';
    
        var post_data = querystring.stringify(dataToPost);
    
        var post_options = {
          host: post_domain,
          port: post_port,
          path: post_path,
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': post_data.length
          }
        };
    
        var post_req = http.request(post_options, function(res) {
          res.setEncoding('utf8');
          res.on('data', function (chunk) {
            console.log('Response: ' + chunk);
          });
        });
    
        // Handle various issues
        post_req.on('error', function(error) { // <-------------------------------- Yeah Buddy!!!
            console.log('ERROR' + error.message);
            // If you need to go on even if there is an error add below line
            //getSomething(i + 1);
        });
        post_req.on("response", function (response) {
            console.log(response);
        });
    
        // write parameters to post body
        post_req.write(post_data);
        post_req.end();
        request.on("response", function (response) {
            console.log(response);
        });
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
Does anyone know how can I replace this 2 symbol below from the string
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have some data like this: 1 2 3 4 5 9 2 6
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I am currently running into a problem where an element is coming back from
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have a text area in my form which accepts all possible characters from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.