diff --git a/connection/listen.go b/connection/listen.go index a7a8376..256a5af 100644 --- a/connection/listen.go +++ b/connection/listen.go @@ -47,11 +47,12 @@ func listenAndAcceptTCP(address string) (*net.TCPConn, error) { return conn, nil } -// Recv returns a read-only channel of byte slices and starts +// RecvChan returns a read-only channel of byte slices and starts // receiving and pushing data into it asynchronously. // The channel is closed when the sender closes the connection. // Use this to read bytes from the network connection. -func (c *Connection) Recv() <-chan []byte { +// The data read is owned by the reader, it is thread-safe to modify. +func (c *Connection) RecvChan() <-chan []byte { c.recvChan = make(chan []byte) go c.recvLoop() return c.recvChan @@ -64,11 +65,13 @@ func (c *Connection) recvLoop() { if err != nil { c.stopFlag = true } - // the underlying memory of the buffer - // must be copied for thread safety - sendBuf := make([]byte, n) - copy(sendBuf, buf) - c.recvChan <- sendBuf + if n > 0 { + // the underlying memory of the buffer + // must be copied for thread safety + sendBuf := make([]byte, n) + copy(sendBuf, buf) + c.recvChan <- sendBuf + } } close(c.recvChan) } diff --git a/main.go b/main.go index 6661a4b..f25c1e3 100644 --- a/main.go +++ b/main.go @@ -19,9 +19,9 @@ func socketExample() { defer conn.Close() fmt.Println("Connection accepted!") - recvChan := conn.Recv() + recvChan := conn.RecvChan() go func() { - time.Sleep(30 * time.Second) + time.Sleep(10 * time.Second) conn.Close() }() for {