Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a simple socket in node.js?

Tags:

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 }); 
like image 298
Mulan Avatar asked Sep 06 '13 18:09

Mulan


2 Answers

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(); 
like image 193
John Williams Avatar answered Oct 02 '22 18:10

John Williams


Try this.

The production code app.js:

var net = require("net");  function createSocket(socket){     var s = socket || new net.Socket();     s.write("hello!"); }  exports.createSocket = createSocket; 

The test code: test.js: (Mocha)

var sinon = require('sinon'),     assert = require('assert'),     net = require('net'),     prod_code=require('./app.js')  describe('Example Stubbing net.Socket', function () {     it("should say hello on connect", function (done) {         var socket = new net.Socket();         var stub = sinon.stub(socket, 'write', function (data, encoding, cb) {             console.log(data);             assert.equal("hello!", data);             done();         });         stub.on = socket.on;         prod_code.createSocket(socket);     }); }); 
like image 33
zs2020 Avatar answered Oct 02 '22 17:10

zs2020