Sending arbitrary data from one peer to another - golang

There is similar question here for JS.

How can a peer send an arbitrarily message to another peer which we know it id (peer_id)?

Imagine a new (node_N) joins to the network. His state is S_0. He propagates his state through pubsub topic. Then other nodes receive his state and now they try to help him to catch up by sending some data. In this case, other nodes can simply send message to node_N instead of broadcasting to all the nodes.

Any idea?

1 Like

You can make all node subscribe to a general topic and also create a private channel through that by sending the peerId that you are trying to send a message to and also introducing an extra check that will only display the message to the node if it matches the peerId when reading the subscription data. This works for me when I tried it out but I believe there are better ways to handle this.


// readLoop pulls messages from the pubsub topic and pushes them onto the Messages channel.
func (cr *ChatRoom) readLoop() {
	for {
		msg, err := cr.sub.Next(cr.ctx)
		if err != nil {
			close(cr.Messages)
			return
		}
		// only forward messages delivered by others
		if msg.ReceivedFrom == cr.self {
			continue
		}
		cm := new(ChatMessage)
		err = json.Unmarshal(msg.Data, cm)
		if err != nil {
			continue
		}
       // only forward message that is meant for sendTo
        if cm.SendTo != shortID(cr.self) {
			continue
		}
		// send valid messages onto the Messages channel
		cr.Messages <- cm
	}
}

i edited this code from this GitHub repo

1 Like

Any better solution?