-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'dev' into 45-cobra-cli
- Loading branch information
Showing
2 changed files
with
78 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
} |