英文:
golang get udp socket buffer size
问题
我正在编写一个UDP客户端,并通过SetWriteBuffer设置UDP套接字的发送缓冲区。
addr, _ := net.ResolveUDPAddr("udp", ":8089")
conn, err := net.DialUDP("udp", nil, addr)
err = conn.SetWriteBuffer(64*1024*1024)
以上是代码示例,我想知道如何测试设置的值是否有效,或者在调用SetWriteBuffer函数后如何获取发送缓冲区的值。谢谢大家。
英文:
I'm writing a udp client and set udp socket send buffer by SetWriteBuffer.
addr, _ := net.ResolveUDPAddr("udp", ":8089")
conn, err :=net.DialUDP("udp", nil, addr)
err =conn.SetWriteBuffer(64*1024*1024)
as above, how can I test set the value is effective or get the send buffer value after call SetWriteBuffer function.
Thank you all.
答案1
得分: 5
在查看net包的代码后,看起来SetWriteBuffer函数会调用setsockopt进行系统调用(对于posix系统)。而GetWriteBuffer没有类似的函数。我能想到的唯一方法是通过另一个系统调用来使用getsockopt函数,代码如下:
addr, _ := net.ResolveUDPAddr("udp", ":8089")
conn, _ := net.DialUDP("udp", nil, addr)
conn.SetWriteBuffer(10 * 1024)
fd, _ := conn.File()
value, _ := syscall.GetsockoptInt(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_SNDBUF)
log.Println(value)
fd.Close()
conn.Close()
英文:
After looking at the net package code, it looks like SetWriteBuffer makes a syscall to setsockopt (for posix). There is no similar function for GetWriteBuffer. The only way i can think to do this is by making another syscall to getsockopt like so.
addr, _ := net.ResolveUDPAddr("udp", ":8089")
conn, _ := net.DialUDP("udp", nil, addr)
conn.SetWriteBuffer(10 * 1024)
fd, _ := conn.File()
value, _ := syscall.GetsockoptInt(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_SNDBUF)
log.Println(value)
fd.Close()
conn.Close()
答案2
得分: 1
检查SetWriteBuffer
返回的错误值。例如,
package main
import (
"log"
"net"
)
func main() {
addr, err := net.ResolveUDPAddr("udp", ":8089")
conn, err := net.DialUDP("udp", nil, addr)
err = conn.SetWriteBuffer(64 * 1024 * 1024)
if err != nil {
log.Print(err)
}
}
请注意,这段代码是用于设置UDP连接的写缓冲区大小。如果SetWriteBuffer
返回错误,将会打印错误信息。
英文:
Check the error value returned by SetWriteBuffer
. For example,
package main
import (
"log"
"net"
)
func main() {
addr, err := net.ResolveUDPAddr("udp", ":8089")
conn, err := net.DialUDP("udp", nil, addr)
err = conn.SetWriteBuffer(64 * 1024 * 1024)
if err != nil {
log.Print(err)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论