Skip to content

Socket connects and gets data from non-existing service #2927

Closed
@rveerd

Description

@rveerd

The following program tries to connect to a TCP service on "localhost". I do not have a service running at port 4096, so it continuously gets ECONNREFUSED, as expected. However, if you let it run long enough (a couple of minutes on my machine), eventually it does connect, sends data and even receives data, which appears to be the same data as was send.

Any ideas what is going on?

It seems this only happens with "localhost" and with higher numbered ports For example, it does not show this behaviour when I try and connect to port 7 (which is also not available on my machine).

This is with Node.js v0.12.7 and Linux 2.6.32-504.el6.x86_64.

/*jslint node:true*/
"use strict";

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(searchString, position) {
        var subjectString = this.toString();
        if (position === undefined || position > subjectString.length) {
            position = subjectString.length;
        }
        position -= searchString.length;
        var lastIndex = subjectString.indexOf(searchString, position);
        return lastIndex !== -1 && lastIndex === position;
    };
}

var net = require("net");

var SERVICE_PORT = 4096;
var SERVICE_HOST = "localhost";

function send(req) {
    var service = new net.Socket();

    service.on("connect", function () {
        console.log("Connected");
        service.setEncoding("utf8");
        service.end(req);
    });

    var line = "";
    service.on("data", function (data) {
        line += data;
        if (line.endsWith("\n")) {
            console.log("Got response [%s]", line.trim());
        }
    });

    service.on("error", function (err) {
        console.error(err);
    });

    service.on("close", function (had_error) {
        if (had_error) {
            console.log("Connection closed WITH ERROR");
            send(req); // Try again.
        } else {
            console.log("Connection closed WITH SUCCESS");
        }
    });

    service.connect(SERVICE_PORT, SERVICE_HOST);
}

send("PING\n");

Example output (last few lines):

Connection closed WITH ERROR
{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }
Connection closed WITH ERROR
{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }
Connection closed WITH ERROR
Connected
Got response [PING]
Connection closed WITH SUCCESS

Metadata

Metadata

Assignees

No one assigned

    Labels

    netIssues and PRs related to the net subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions