Skip to content

Commit

Permalink
Merge branch 'dev' into 45-cobra-cli
Browse files Browse the repository at this point in the history
  • Loading branch information
jordanschalm committed Jun 3, 2017
2 parents 3886a64 + 3c1b3ab commit 5dfa1bd
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
25 changes: 25 additions & 0 deletions conn/conn.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package conn

import "net"

// Dial opens a connection to a remote host. `host` should be a string
// in the format <IP>|<hostname>:<port>
func Dial(host string) (net.Conn, error) {
return net.Dial("tcp", host)
}

// Listen binds to a TCP port and waits for incoming connections.
// When a connection is accepted, dispatches to the handler.
func Listen(iface string, handler func(net.Conn)) error {
listener, err := net.Listen("tcp", iface)
if err != nil {
return err
}
for {
c, err := listener.Accept()
if err != nil {
return err
}
go handler(c)
}
}
53 changes: 53 additions & 0 deletions conn/conn_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package conn

import (
"fmt"
"net"
"sync"
"testing"
"time"
)

func TestConnect(t *testing.T) {
_, err := Dial("www.google.ca:80")
if err != nil {
fmt.Println(err.Error())
t.Fail()
}
}

func TestListen(t *testing.T) {
wg := sync.WaitGroup{}
wg.Add(5)

handler := func(c net.Conn) {
defer c.Close()
buf := make([]byte, 1)
n, err := c.Read(buf)
if err != nil {
t.Fail()
}
if n != 1 {
t.Fail()
}
wg.Done()
}

go Listen(":8080", handler)
// Sleep to guarantee that our listener is ready when we start making connections
time.Sleep(time.Millisecond)

for i := 0; i < 5; i++ {
go func() {
c, err := Dial(":8080")
if err != nil {
t.Fail()
return
}
c.Write([]byte{byte(i)})
}()
}

wg.Wait()
fmt.Println("ending")
}

0 comments on commit 5dfa1bd

Please sign in to comment.