holepunchto / hyperswarm

A distributed networking stack for connecting peers.
https://docs.holepunch.to
MIT License
1.06k stars 85 forks source link

Using Sockets in Hyperswarm #53

Closed rlingineni closed 4 years ago

rlingineni commented 4 years ago

I'm a little new to using Hyperswarm and moreover the entire space of communicating via Sockets.

I'm trying to build a simple chat application between two peers on the same machine. Super basic but just so I can try out Hyperswarm on a basic level.

I have two files that are both running the same code:

swarm.on("connection", (socket, details) => {
    console.log("new connection!", details);
    socket.write("send-message", { msg: "Client 1 has Joined" });
    socket.on("send-message", data => {
        console.log(data.msg);
        AskForUserInput(socket);
    });
});

function AskForUserInput(socket) {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.question("What do you want to say: ", (answer) => {
        socket.write("send-message", { msg: "Client 2: " + answer });
        rl.close();
    });
}

Running the program in two terminals - I can see that they have both connected to each other, but I don't see any messages being transmitted. Is there something wrong with my approach?

RangerMauve commented 4 years ago

Hi, I think your example is assuming that sockets behave kind of like socket.io where you can emit events on either side. Sadly, that isn't the case as sockets in Node are Duplex Streams which can only work with writing binary data.

I'd suggest looking into ndjson streams which will enable you to send objects between the two sides and have some sort of type field for the message type along with whatever other data you want for your message.

mafintosh commented 4 years ago

What @RangerMauve said