goadb/dialer.go
Zach Klippenstein 9f7d11a3bc Refactored ClientConfig into a Server interface.
* StartServer is now a method on Server.
* What used to be Dialer.Dial is now Server.Dial.
* Server.Dial handles trying to start the server if the initial connection fails.
* Dialer now dials a network address.
* All types that took a Dialer now take a Server.
* Server now has tests!
2016-01-10 14:01:58 -08:00

44 lines
1.3 KiB
Go

package goadb
import (
"io"
"net"
"runtime"
"github.com/zach-klippenstein/goadb/util"
"github.com/zach-klippenstein/goadb/wire"
)
// Dialer knows how to create connections to an adb server.
type Dialer interface {
Dial(address string) (*wire.Conn, error)
}
type tcpDialer struct{}
// Dial connects to the adb server on the host and port set on the netDialer.
// The zero-value will connect to the default, localhost:5037.
func (tcpDialer) Dial(address string) (*wire.Conn, error) {
netConn, err := net.Dial("tcp", address)
if err != nil {
return nil, util.WrapErrorf(err, util.ServerNotAvailable, "error dialing %s", address)
}
// net.Conn can't be closed more than once, but wire.Conn will try to close both sender and scanner
// so we need to wrap it to make it safe.
safeConn := wire.MultiCloseable(netConn)
// Prevent leaking the network connection, not sure if TCPConn does this itself.
// Note that the network connection may still be in use after the conn isn't (scanners/senders
// can give their underlying connections to other scanner/sender types), so we can't
// set the finalizer on conn.
runtime.SetFinalizer(safeConn, func(conn io.ReadWriteCloser) {
conn.Close()
})
return &wire.Conn{
Scanner: wire.NewScanner(safeConn),
Sender: wire.NewSender(safeConn),
}, nil
}