This is a created article in which the information may have evolved or changed.
Problem
Golang cannot be multiplexed, select can only support channel read and write, do not support socket read and write. So the question is, how to read and write efficiently to the socket?
Analysis
Sockets are capable of concurrently reading and writing
Pkg/net Documentation:
Multiple Goroutines may invoke methods on a Conn simultaneously.
Read
In order to avoid sending fast, receiving and processing slow leads to blocking, it is necessary to have a dedicated co-process responsible for reading from the socket, read as soon as possible. After reading it, it is recommended to send the business process directly through the channel to avoid time consuming.
If the queue waits for a business to receive, it can also be slow, causing the data to accumulate. Not recommended.
Write
Although write can be called concurrently by multiple threads, write may write only partially success. Therefore, if multiple concurrent write, the message may cross. So it needs to be written in a unified process.
Scheme
- 1, each socket has a read and a write to the co-process
- 2, read the association to read from the socket as soon as possible, only do a small amount of time-consuming processing, time-consuming processing to the business process
- 3, write to the input queue, call write. A business call to send may be blocked or error if the queue is full.