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,12 +65,14 @@ func (c *Connection) recvLoop() {
if err != nil { if err != nil {
c.stopFlag = true c.stopFlag = true
} }
if n > 0 {
// the underlying memory of the buffer // the underlying memory of the buffer
// must be copied for thread safety // must be copied for thread safety
sendBuf := make([]byte, n) sendBuf := make([]byte, n)
copy(sendBuf, buf) copy(sendBuf, buf)
c.recvChan <- sendBuf 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 {