How should the socket be used in Golang?

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.