neoneo-go/pkg/network/peer.go

52 lines
1.1 KiB
Go
Raw Normal View History

2018-01-26 18:04:13 +00:00
package network
import (
"log"
"net"
2018-01-29 18:17:49 +00:00
"github.com/anthdm/neo-go/pkg/util"
2018-01-26 18:04:13 +00:00
)
// Peer represents a remote node, backed by TCP transport.
type Peer struct {
2018-01-28 13:59:32 +00:00
id uint32
// underlying TCP connection
2018-01-26 18:04:13 +00:00
conn net.Conn
2018-01-29 18:17:49 +00:00
// host and port information about this peer.
endpoint util.Endpoint
// channel to coordinate messages writen back to the connection.
2018-01-26 18:04:13 +00:00
send chan *Message
2018-01-29 18:17:49 +00:00
// whether this peers version was acknowledged.
2018-01-26 18:04:13 +00:00
verack bool
}
// NewPeer returns a (TCP) Peer.
2018-01-29 18:17:49 +00:00
func NewPeer(conn net.Conn) *Peer {
e, _ := util.EndpointFromString(conn.RemoteAddr().String())
2018-01-26 18:04:13 +00:00
return &Peer{
2018-01-29 18:17:49 +00:00
conn: conn,
send: make(chan *Message),
endpoint: e,
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)
}
}
}