英文:
golang TCPConn.Write method call
问题
我想通过TCP发送数据,但我不知道是直接调用Write方法还是在for循环中调用Write方法。
所以我想知道下面这些函数中哪个是正确的。
func sendData_Method2(data string) {
/*
方法tcpConn.Write将被阻塞,直到所有数据发送完毕。
*/
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", "127.0.0.1", 8899))
if err != nil {
log.Println(err)
return
}
tcpConn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
log.Println(err)
return
}
defer tcpConn.Close()
if _, err := tcpConn.Write([]byte(data)); err != nil {
log.Println(err)
}
}
func sendData_Method1(data string) {
/*
需要在for循环中调用方法tcpConn.Write,直到所有数据发送完毕。
*/
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", "127.0.0.1", 8899))
if err != nil {
log.Println(err)
return
}
tcpConn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
log.Println(err)
return
}
defer tcpConn.Close()
dataWillSend := []byte(data)
lengthOfWillSend := len(dataWillSend)
startPosi := 0
for {
n, err := tcpConn.Write(dataWillSend[startPosi:])
if err != nil {
log.Println(err)
return
}
lengthOfWillSend -= n
startPosi = n
if lengthOfWillSend == 0 {
break
}
}
}
英文:
I want to send data out via TCP, but I do not know should call Write method directly or call Write method in for loop.
So I want to know these functions below which is corrent.
func sendData_Method2(data string) {
/*
method tcpConn.Write will be blocked until all data sent out.
*/
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", "127.0.0.1", 8899))
if err != nil {
log.Println(err)
return
}
tcpConn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
log.Println(err)
return
}
defer tcpConn.Close()
if _, err := tcpConn.Write([]byte(data)); err != nil {
log.Println(err)
}
}
func sendData_Method1(data string) {
/*
need call method tcpConn.Write in for loop until all data sent out.
*/
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", "127.0.0.1", 8899))
if err != nil {
log.Println(err)
return
}
tcpConn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
log.Println(err)
return
}
defer tcpConn.Close()
dataWillSend := []byte(data)
lengthOfWillSend := len(dataWillSend)
startPosi := 0
for {
n, err := tcpConn.Write(dataWillSend[startPosi:])
if err != nil {
log.Println(err)
return
}
lengthOfWillSend -= n
startPosi = n
if lengthOfWillSend == 0 {
break
}
}
}
答案1
得分: 1
根据io.Write
的文档:
Write函数将p中的len(p)字节写入底层数据流。它返回从p中写入的字节数(0 <= n <= len(p))以及导致写入提前停止的任何错误。如果返回的n < len(p),Write必须返回一个非nil的错误。
因此,你可以直接调用Write
而无需使用循环。
英文:
According to io.Write
documentation:
> Write writes len(p) bytes from p to the underlying data stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-nil error if it returns n < len(p).
So, you can simply call Write
without a loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论