Official Go implementation of the Ethereum protocol
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-ethereum/peer.go

93 lines
2.0 KiB

11 years ago
package main
import (
"net"
"log"
"github.com/ethereum/ethwire-go"
11 years ago
)
type Peer struct {
11 years ago
// Server interface
11 years ago
server *Server
11 years ago
// Net connection
11 years ago
conn net.Conn
11 years ago
// Output queue which is used to communicate and handle messages
outputQueue chan ethwire.InOutMsg
11 years ago
// Quit channel
11 years ago
quit chan bool
}
func NewPeer(conn net.Conn, server *Server) *Peer {
return &Peer{
outputQueue: make(chan ethwire.InOutMsg, 1), // Buffered chan of 1 is enough
11 years ago
quit: make(chan bool),
server: server,
conn: conn,
}
}
// Outputs any RLP encoded data to the peer
func (p *Peer) QueueMessage(msgType string, data []byte) {
p.outputQueue <- ethwire.InOutMsg{MsgType: msgType, Data: data}
11 years ago
}
11 years ago
// Outbound message handler. Outbound messages are handled here
11 years ago
func (p *Peer) HandleOutbound() {
out:
for {
select {
11 years ago
// Main message queue. All outbound messages are processed through here
case msg := <-p.outputQueue:
11 years ago
// TODO Message checking and handle accordingly
err := ethwire.WriteMessage(p.conn, msg)
if err != nil {
log.Println(err)
// Stop the client if there was an error writing to it
p.Stop()
}
11 years ago
// Break out of the for loop if a quit message is posted
11 years ago
case <- p.quit:
break out
}
}
}
11 years ago
// Inbound handler. Inbound messages are received here and passed to the appropriate methods
11 years ago
func (p *Peer) HandleInbound() {
defer p.Stop()
11 years ago
out:
for {
11 years ago
// Wait for a message from the peer
msg, err := ethwire.ReadMessage(p.conn)
11 years ago
if err != nil {
log.Println(err)
break out
}
// TODO
data, _ := Decode(msg.Data, 0)
log.Printf("%s, %s\n", msg.MsgType, data)
11 years ago
}
// Notify the out handler we're quiting
p.quit <- true
}
func (p *Peer) Start() {
11 years ago
// Run the outbound handler in a new goroutine
11 years ago
go p.HandleOutbound()
11 years ago
// Run the inbound handler in a new goroutine
11 years ago
go p.HandleInbound()
}
func (p *Peer) Stop() {
p.conn.Close()
p.quit <- true
}