From af09d4e09cf6845e73da1cfa19ef1d59b351f624 Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Sat, 17 Feb 2024 14:13:59 -0500 Subject: [PATCH] Adding example files from ch3 --- network_programming/tcp/ch3/dail_test.go | 66 ++++++++++++++++++++++ network_programming/tcp/ch3/listen_test.go | 31 ++++++++++ 2 files changed, 97 insertions(+) create mode 100644 network_programming/tcp/ch3/dail_test.go create mode 100644 network_programming/tcp/ch3/listen_test.go diff --git a/network_programming/tcp/ch3/dail_test.go b/network_programming/tcp/ch3/dail_test.go new file mode 100644 index 0000000..806a941 --- /dev/null +++ b/network_programming/tcp/ch3/dail_test.go @@ -0,0 +1,66 @@ +package ch3 + +import ( + "io" + "net" + "testing" +) + +func TestDial(t *testing.T) { + //create a listener on a random port to make out test connection to + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + + // channel that receives struct objects + done := make(chan struct{}) + + // Goroutine (aka handler) for listening for connections + go func() { + defer func() { done <- struct{}{} }() + + for { + conn, err := listener.Accept() + if err != nil { + t.Log(err) + return + } + // goroutine for responding to connection requests + go func(c net.Conn) { + defer func() { + c.Close() + done <- struct{}{} + }() + + // create a slice of size 1024 (1 kilobyte) + buf := make([]byte, 1024) + for { + // reads up to 1024 bytes at a time from the socket + n, err := c.Read(buf) + if err != nil { + // c.Read returns io.EOF when FIN packet (graceful termination) is received + if err != io.EOF { + t.Error(err) + } + return + } + // logs the bytes it receives + t.Logf("received: %q", buf[:n]) + } + }(conn) + + } + }() + + // Now we make our client + conn, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + + conn.Close() + <-done + listener.Close() + <-done +} diff --git a/network_programming/tcp/ch3/listen_test.go b/network_programming/tcp/ch3/listen_test.go new file mode 100644 index 0000000..9fc56d9 --- /dev/null +++ b/network_programming/tcp/ch3/listen_test.go @@ -0,0 +1,31 @@ +package ch3 + +import ( + "net" + "testing" +) + +func TestListener(t *testing.T) { + listener, err := net.Listen("tcp", "0.0.0.0:0") + if err != nil { + t.Fatal(err) + } + + defer func() { _ = listener.Close() }() + + t.Logf("bound to port %q", listener.Addr()) + + // example for handling connections and processing connections in a goroutine + // for { + // conn, err := listener.Accept() + // if err != nil { + // t.Fatal(err) + // } + + // go func(c net.Conn) { + // defer c.Close() + // // Your code goes here to handle the connection + // }(conn) + // } + +}