Improve networking code

This commit is contained in:
Kristóf Tóth 2020-04-30 13:03:06 +02:00
parent 1985c0df4f
commit a895ee9761
2 changed files with 12 additions and 9 deletions

View File

@ -47,11 +47,12 @@ func listenAndAcceptTCP(address string) (*net.TCPConn, error) {
return conn, nil 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. // receiving and pushing data into it asynchronously.
// The channel is closed when the sender closes the connection. // The channel is closed when the sender closes the connection.
// Use this to read bytes from the network 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) c.recvChan = make(chan []byte)
go c.recvLoop() go c.recvLoop()
return c.recvChan return c.recvChan
@ -64,11 +65,13 @@ func (c *Connection) recvLoop() {
if err != nil { if err != nil {
c.stopFlag = true c.stopFlag = true
} }
// the underlying memory of the buffer if n > 0 {
// must be copied for thread safety // the underlying memory of the buffer
sendBuf := make([]byte, n) // must be copied for thread safety
copy(sendBuf, buf) sendBuf := make([]byte, n)
c.recvChan <- sendBuf copy(sendBuf, buf)
c.recvChan <- sendBuf
}
} }
close(c.recvChan) close(c.recvChan)
} }

View File

@ -19,9 +19,9 @@ func socketExample() {
defer conn.Close() defer conn.Close()
fmt.Println("Connection accepted!") fmt.Println("Connection accepted!")
recvChan := conn.Recv() recvChan := conn.RecvChan()
go func() { go func() {
time.Sleep(30 * time.Second) time.Sleep(10 * time.Second)
conn.Close() conn.Close()
}() }()
for { for {