goadb/dialer.go

82 lines
1.6 KiB
Go
Raw Normal View History

2015-07-11 21:32:04 +00:00
package goadb
import (
"fmt"
"net"
"runtime"
2015-07-11 21:32:04 +00:00
2015-07-12 06:18:58 +00:00
"github.com/zach-klippenstein/goadb/util"
2015-07-11 21:32:04 +00:00
"github.com/zach-klippenstein/goadb/wire"
)
const (
// Default port the adb server listens on.
AdbPort = 5037
)
/*
Dialer knows how to create connections to an adb server.
*/
type Dialer interface {
2015-07-11 21:32:04 +00:00
Dial() (*wire.Conn, error)
}
2015-07-11 21:32:04 +00:00
/*
NewDialer creates a new Dialer.
2015-07-11 21:32:04 +00:00
If host is "" or port is 0, "localhost:5037" is used.
*/
func NewDialer(host string, port int) Dialer {
2015-07-11 21:32:04 +00:00
if host == "" {
host = "localhost"
}
if port == 0 {
port = AdbPort
}
return &netDialer{host, port}
}
2015-07-11 21:32:04 +00:00
type netDialer struct {
Host string
Port int
}
func (d *netDialer) String() string {
return fmt.Sprintf("netDialer(%s:%d)", d.Host, d.Port)
}
// 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.
2015-07-11 21:32:04 +00:00
func (d *netDialer) Dial() (*wire.Conn, error) {
host := d.Host
port := d.Port
2015-07-12 06:18:58 +00:00
address := fmt.Sprintf("%s:%d", host, port)
netConn, err := net.Dial("tcp", address)
if err != nil {
2015-07-12 06:18:58 +00:00
return nil, util.WrapErrorf(err, util.NetworkError, "error dialing %s", address)
}
2015-07-11 21:32:04 +00:00
conn := &wire.Conn{
Scanner: wire.NewScanner(netConn),
Sender: wire.NewSender(netConn),
}
// Prevent leaking the network connection, not sure if TCPConn does this itself.
runtime.SetFinalizer(netConn, func(conn *net.TCPConn) {
conn.Close()
})
return conn, nil
}
2015-07-11 21:32:04 +00:00
func roundTripSingleResponse(d Dialer, req string) ([]byte, error) {
conn, err := d.Dial()
if err != nil {
return nil, err
}
defer conn.Close()
return conn.RoundTripSingleResponse([]byte(req))
}