Simplify BtcdHandler.

This commit is contained in:
Josh Rickmar 2013-11-21 15:49:07 -05:00
parent 935335f1a5
commit 21faab5e3e

View file

@ -54,7 +54,7 @@ var (
// Channel to send messages btcwallet does not understand and requests // Channel to send messages btcwallet does not understand and requests
// from btcwallet to btcd. // from btcwallet to btcd.
btcdMsgs = make(chan []byte, 100) btcdMsgs = make(chan []byte)
// Adds a frontend listener channel // Adds a frontend listener channel
addFrontendListener = make(chan (chan []byte)) addFrontendListener = make(chan (chan []byte))
@ -272,37 +272,30 @@ func frontendSendRecv(ws *websocket.Conn) {
// BtcdHandler listens for replies and notifications from btcd over a // BtcdHandler listens for replies and notifications from btcd over a
// websocket and sends messages that btcwallet does not understand to // websocket and sends messages that btcwallet does not understand to
// btcd. Unlike FrontendHandler, exactly one BtcdHandler goroutine runs. // btcd. Unlike FrontendHandler, exactly one BtcdHandler goroutine runs.
// BtcdHandler spawns goroutines to perform these tasks, and closes the
// done channel once they are finished.
func BtcdHandler(ws *websocket.Conn, done chan struct{}) { func BtcdHandler(ws *websocket.Conn, done chan struct{}) {
// Listen for replies/notifications from btcd, and decide how to handle them. // Listen for replies/notifications from btcd, and decide how to handle them.
replies := make(chan []byte) replies := make(chan []byte)
go func() { go func() {
defer close(replies)
for { for {
select {
case <-done:
return
default:
var m []byte var m []byte
if err := websocket.Message.Receive(ws, &m); err != nil { if err := websocket.Message.Receive(ws, &m); err != nil {
close(done) log.Debugf("cannot recevie btcd message: %v", err)
close(replies)
return return
} }
replies <- m replies <- m
} }
}
}() }()
go func() { go func() {
defer close(done)
for { for {
select { select {
case <-done:
return
case rply, ok := <-replies: case rply, ok := <-replies:
if !ok { if !ok {
// btcd disconnected // btcd disconnected
close(done)
return return
} }
// Handle message here. // Handle message here.
@ -312,7 +305,6 @@ func BtcdHandler(ws *websocket.Conn, done chan struct{}) {
if err := websocket.Message.Send(ws, r); err != nil { if err := websocket.Message.Send(ws, r); err != nil {
// btcd disconnected. // btcd disconnected.
log.Errorf("Unable to send message to btcd: %v", err) log.Errorf("Unable to send message to btcd: %v", err)
close(done)
return return
} }
} }
@ -646,6 +638,7 @@ func BtcdConnect(certificates []byte, reply chan error) {
return return
} }
// done is closed when BtcdHandler's goroutines are finished.
<-done <-done
reply <- ErrConnLost reply <- ErrConnLost
} }