Always send Hello on NewClient

This commit is contained in:
Henry
2014-02-11 13:10:24 +01:00
parent ce26df96ac
commit 9de2fd3f5b
4 changed files with 23 additions and 38 deletions

View File

@ -13,10 +13,12 @@ type Client struct {
toSam *bufio.Writer
}
// create a new client, connecting to the default host:port at localhost:7656
func NewDefaultClient() (*Client, error) {
return NewClient("localhost:7656")
}
// create a new client, connecting to a specified port
func NewClient(addr string) (*Client, error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
@ -27,40 +29,29 @@ func NewClient(addr string) (*Client, error) {
fromSam: bufio.NewReader(conn),
toSam: bufio.NewWriter(conn),
}
return c, nil
return c, c.hello()
}
func (c *Client) Hello() (err error) {
if _, err = c.toSam.WriteString("HELLO VERSION MIN=3.0 MAX=3.0\n"); err != nil {
// send the initial handshake command and check that the reply is ok
func (c *Client) hello() (err error) {
const hello = "HELLO VERSION MIN=3.0 MAX=3.0\n"
var r *Reply
r, err = c.sendCmd(hello)
if err != nil {
return err
}
if err = c.toSam.Flush(); err != nil {
return err
if r.Topic != "HELLO" {
return fmt.Errorf("Unknown Reply: %+v\n", r)
}
for {
line, err := c.fromSam.ReadString('\n')
if err != nil {
return err
}
reply, err := parseReply(line)
if err != nil {
return err
}
if reply.Topic != "HELLO" {
return fmt.Errorf("Unknown Reply: %+v\n", reply)
}
if reply.Pairs["RESULT"] != "OK" {
return fmt.Errorf("Handshake did not succeed")
}
break
if r.Pairs["RESULT"] != "OK" || r.Pairs["VERSION"] != "3.0\n" {
return fmt.Errorf("Handshake did not succeed\nReply:%+v\n", r)
}
return nil
}
func (c *Client) Close() error {

View File

@ -23,11 +23,10 @@ func teardown() {
func TestClientHello(t *testing.T) {
var err error
setup()
defer teardown()
err = client.Hello()
client, err = NewDefaultClient()
if err != nil {
t.Errorf("client.Hello() should not throw an error.\n%s\n", err)
}
client.Close()
}

View File

@ -8,7 +8,10 @@ import (
// implements the net.Dial function to be used as http.Transport
func (c *Client) Dial(network, addr string) (net.Conn, error) {
addr = addr[:strings.Index(addr, ":")]
portIdx := strings.Index(addr, ":")
if portIdx >= 0 {
addr = addr[:portIdx]
}
addr, err := c.Lookup(addr)
if err != nil {
return nil, err
@ -26,10 +29,6 @@ func (c *Client) Dial(network, addr string) (net.Conn, error) {
return nil, err
}
if newC.Hello() != nil {
return nil, err
}
fmt.Println("newC Hello OK")
if newC.StreamConnect(id, addr) != nil {

View File

@ -11,8 +11,6 @@ func TestClientLookupInvalid(t *testing.T) {
setup()
defer teardown()
client.Hello()
addr, err := client.Lookup("abci2p")
if addr != "" || err == nil {
t.Error("client.Lookup() should throw an error.")
@ -30,8 +28,6 @@ func ExampleClient_Lookup() {
setup()
defer teardown()
client.Hello()
_, err = client.Lookup("zzz.i2p")
if err != nil {
fmt.Printf("client.Lookup() should not throw an error.\n%s\n", err)