I create a tcp connection pool in golang and set every connection to keep alive, when I get a connection from pool, I will set a 10 seconds timeout by SetDeadline function. Now I want to know, if a timeout error occur after reading from a connection and server send message to me after this point, will the message be put into my connection receive buffer? Will I get the message in next reading? If so, how should I handle the timeout error? Close the connection and create a new one?
1条回答 默认 最新
- douhong4452 2018-03-19 12:54关注
If a timeout error occur after reading from a connection and server send message to me after this point, will the message be put into my connection receive buffer?
If you don't close the connection, yes.
Will I get the message in next reading?
Yes, if you reset the deadline. Although this does beg the question why you set a timeout in the first place.
package main import ( "fmt" "io" "log" "net" "time" ) func main() { l, err := net.Listen("tcp", "127.0.0.1:3001") check(err) go slowServer(l) conn, err := net.Dial("tcp", "127.0.0.1:3001") check(err) conn.SetDeadline(time.Now().Add(time.Second)) b := make([]byte, 512) n, err := conn.Read(b) fmt.Printf("%q, %v ", b[:n], err) // "", i/o timeout // Reset deadline conn.SetDeadline(time.Now().Add(2 * time.Second)) n, err = conn.Read(b) fmt.Printf("%q, %v ", b[:n], err) // "hello world", <nil> } func slowServer(l net.Listener) { conn, err := l.Accept() check(err) time.Sleep(2 * time.Second) io.WriteString(conn, "hello world") conn.Close() } func check(err error) { if err != nil { log.Fatal(err) } } // "", read tcp 127.0.0.1:50488->127.0.0.1:3001: i/o timeout // "hello world", <nil>
Try it on the playground: https://play.golang.org/p/Id60hHK7tKF
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
- ¥15 如何在scanpy上做差异基因和通路富集?
- ¥20 关于#硬件工程#的问题,请各位专家解答!
- ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
- ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
- ¥30 截图中的mathematics程序转换成matlab
- ¥15 动力学代码报错,维度不匹配
- ¥15 Power query添加列问题
- ¥50 Kubernetes&Fission&Eleasticsearch
- ¥15 報錯:Person is not mapped,如何解決?