How to create a simple socket in node.js?


Question

I'm trying to create a dummy socket for use in some of my tests

var net = require("net");

var s = new net.Socket();

s.on("data", function(data) {
  console.log("data received:", data);
});

s.write("hello!");

Getting this error

Error: This socket is closed.

I've also tried creating the socket with

var s = new net.Socket({allowHalfOpen: true});

What am I doing wrong?


For reference, the complete test looks like this

it("should say hello on connect", function(done) {

  var socket = new net.Socket();

  var client = Client.createClient({socket: socket});

  socket.on("data", function(data){
    assert.equal("hello", data);
    done();
  });

  client.connect();
  // writes "hello" to the socket
});
1
19
9/6/2013 8:23:36 PM

I don't think the server is put into listening state. This what I use..

// server
require('net').createServer(function (socket) {
    console.log("connected");

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

.listen(8080);

// client
var s = require('net').Socket();
s.connect(8080);
s.write('Hello');
s.end();

Client only..

var s = require('net').Socket();
s.connect(80, 'google.com');
s.write('GET http://www.google.com/ HTTP/1.1\n\n');

s.on('data', function(d){
    console.log(d.toString());
});

s.end();
34
9/6/2013 7:27:59 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon