telehash / telehash-js

telehash javascript module for node.js and browserify
http://telehash.org
MIT License
301 stars 51 forks source link

Receiving on stream #53

Closed csdrane closed 8 years ago

csdrane commented 8 years ago

I have two code snippets below. 1.js accepts the stream from 2.js, and outputs the message written to it by 2. 1 tries to send a message to 2 as well, but for some reason this is failing. Eyeballing this against the echo.js example, I have no clue what I'm missing. I suspect it has to do with the fact that it is the client that created the stream. I tried adding a stream handler to 2.js but this didn't resolve the problem. I'm guessing I'm probably making a small error somewhere but it's escaping me.

1.js

th.load({id: id}, function(e, mesh) {
  mesh.discover(true);
  mesh.accept = function(from) {
    mesh.link(from);
    console.log("INCOMING:", from.hashname);
  };

  mesh.stream(function(link, args, accept) {
    console.log("INCOMING STREAM");
    var chan = accept();

    chan.on('data', function(d) {
      try {
        var msg = JSON.parse(d);
      } catch (e) {
        return console.log('Error parsing', d);
      }
      console.log("MSG", msg);
    });

    chan.write(JSON.stringify({a: "reply"}));
  });
});

2.js

mesh({id: id}, function(e, mesh) {
  mesh.discover(true);
  mesh.accept = function(from) {
    console.log('mesh.accept');
    var link = mesh.link(from);
    var chan = link.stream();

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

    chan.write(JSON.stringify({}));
  };
});
csdrane commented 8 years ago

Looks like this was because 2.js needed the chan related code wrapped in link.on('status', ...). Debugging this was confusing, since stream writes worked properly. I also note that if var chan = link.stream(); is placed outside the status event that reads will again be broken, and writes will again work as intended.

csdrane commented 8 years ago

Closing as no further action required.