Improve networking code
This commit is contained in:
parent
1985c0df4f
commit
a895ee9761
@ -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,12 +65,14 @@ func (c *Connection) recvLoop() {
|
||||
if err != nil {
|
||||
c.stopFlag = true
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user