neoneo-go/pkg/network/peer.go

47 lines
1 KiB
Go
Raw Normal View History

2018-01-26 18:04:13 +00:00
package network
import (
"log"
"net"
)
// Peer represents a remote node, backed by TCP transport.
type Peer struct {
// underlaying TCP connection
conn net.Conn
// channel to coordinate message writes back to the connection.
send chan *Message
// verack is true if this node has sended it's version.
verack bool
// whether we or him made the initial connection.
initiator bool
2018-01-26 18:04:13 +00:00
}
// NewPeer returns a (TCP) Peer.
func NewPeer(conn net.Conn, init bool) *Peer {
2018-01-26 18:04:13 +00:00
return &Peer{
conn: conn,
send: make(chan *Message),
initiator: init,
2018-01-26 18:04:13 +00:00
}
}
// writeLoop writes messages to the underlying TCP connection.
// A goroutine writeLoop is started for each connection.
// There should be at most one writer to a connection executing
// all writes from this goroutine.
func (p *Peer) writeLoop() {
// clean up the connection.
defer func() {
p.conn.Close()
}()
for {
msg := <-p.send
2018-01-27 15:47:43 +00:00
rpcLogger.Printf("OUT :: %s", msg.commandType())
2018-01-26 18:04:13 +00:00
if err := msg.encode(p.conn); err != nil {
log.Printf("encode error: %s", err)
}
}
}