TCP reading is not blocked

I am trying to make the server and client in Go, I was able to contact the server and client. But the problem is that TCP read in golang does not block. What I would like to know is it possible for golang to block reading as read in C. Thank you.

EDIT:

Here is the server source code:

func Init_tcp() *net.TCPListener { laddr, err := net.ResolveTCPAddr("tcp", ":4243") if err != nil { log.Fatal(err) } tcp, err := net.ListenTCP("tcp", laddr) if err != nil { log.Fatal(err) } return tcp } func main() { tcp := Init_tcp() conn, _ := tcp.Accept() data := make([]byte, 512) conn.SetNoDelay(false) for { conn.Read(data) fmt.Println(data) } } 

and my client:

 func Init_tcp() *net.TCPConn { laddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:4243") if err != nil { log.Fatal(err) } tcp, err := net.DialTCP("tcp", nil, laddr) if err != nil { log.Fatal(err) } return tcp } func main() { tcp := Init_tcp() tcp.Write([]byte("hello world")) } 
+7
c go tcp
source share
1 answer

Reader can return partial data. From docs : "If some data is available but not len ​​(p) bytes, Read usually returns what is available, rather than waiting for more."

This is a problem in any language, even if something like this happened to you in C: TCP just provides a byte stream that can be written at any time. Separate records can be split into several packets for transmission, and there is no built-in signal for the receiver telling where one record / message / request ends. The application must figure out its own path to the signal boundaries. This can mean delimiters ( \n ) or implicit or explicit byte counts (HTTP Content-Length is explicit).

To read a specific number of input bytes, you want io.ReadAtLeast or io.ReadFull . To read until an arbitrary condition is met, you simply have to loop through the Read call until there is an error. (Then you may need an error on too large inputs to prevent a bad client from using server resources.) If you are using a text protocol, you should consider net/textproto , which puts bufio.Reader before the connection, so you can read the lines. To limit how long you will wait to finish reading (so that a bad client cannot leave the scroll and use memory, etc. Forever), look at net with Deadline in the name (which are associated with Timeout functions in Error types). The context package helps manage timeouts, deadlines and cancellations, and is especially useful if, for example, you write a complex server that is going to perform many network operations for each request.

The sample code has a possibly unrelated, but important problem: it removes errors from Read and Write . This can mask simple problems and make debugging difficult. If you have problems after accounting for partial reads, check all errors before contacting for further assistance. Take a look errcheck so that errors like this do not get into production.

+27
source share

All Articles