diff --git a/conn/conn.go b/conn/conn.go new file mode 100644 index 0000000..c6d7975 --- /dev/null +++ b/conn/conn.go @@ -0,0 +1,25 @@ +package conn + +import "net" + +// Dial opens a connection to a remote host. `host` should be a string +// in the format |: +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) + } +} diff --git a/conn/conn_test.go b/conn/conn_test.go new file mode 100644 index 0000000..32f30fc --- /dev/null +++ b/conn/conn_test.go @@ -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") +}