From a895ee9761a91fbbe23bbc55c2d261cdab5c261f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Thu, 30 Apr 2020 13:03:06 +0200 Subject: [PATCH] Improve networking code --- connection/listen.go | 17 ++++++++++------- main.go | 4 ++-- 2 files changed, 12 insertions(+), 9 deletions(-) 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 {