network: write messages atomically

Right now message can be written in several Write's so
concurrent calls of writeMsg() can in theory interleave.
This commit fixes it.

Signed-off-by: Evgenii Stratonikov <evgeniy@nspcc.ru>
This commit is contained in:
Evgenii Stratonikov 2019-11-16 12:42:03 +03:00
parent 394af5f777
commit e3098ed0f8

View file

@ -63,8 +63,14 @@ func (p *TCPPeer) writeMsg(msg *Message) error {
case err := <-p.done:
return err
default:
w := io.NewBinWriterFromIO(p.conn)
return msg.Encode(w)
w := io.NewBufBinWriter()
if err := msg.Encode(w.BinWriter); err != nil {
return err
}
_, err := p.conn.Write(w.Bytes())
return err
}
}