Beispiel #1
0
func (n *Network) handleSend(msg Message) {
	connMsg := connection.NewMessage(msg.Endpoint, msg.Type, msg.Data)
	if msg.Endpoint == "" {
		// Broadcast message to all connected peers.
		for _, p := range n.peers {
			if p.isConnected() {
				msg.Endpoint = p.name()
				// Send is non-blocking. It might fail if the
				// connection's send buffer is full, but we don't
				// care about that for broadcasts.
				_ = connection.Send(p.conn, connMsg)
			}
		}
	} else {
		p, err := findConnectedPeer(n.peers, msg.Endpoint)
		if err != nil {
			log.Printf("Can't send message: %v", err)
		} else {
			if err := connection.Send(p.conn, connMsg); err != nil {
				log.Println(err)
			}
		}
	}
}
Beispiel #2
0
// connected will associate an established connection with the peer.
func (p *peer) connected(c connection.Conn) error {
	if c.Endpoint() != p.name() {
		log.Fatalf("Attempted to associate connection to %q with peer %q.",
			c.Endpoint(), p.name())
	}
	p.pending = false
	if err := c.Error(); err != nil {
		p.FailureTime = time.Now()
		p.lastError = err
		return err
	}
	p.conn = c
	c.Run(p.receiveCh)

	// Ask the peer what other addresses in the network it knows about.
	connection.Send(c, connection.Message{
		Endpoint: p.name(),
		Type:     "getaddr",
	})
	return nil
}