golang网络通信超时设置
网络通信中,为了防止长时间无响应的情况,经常会用到网络连接超时、读写超时的设置。
本文结合例子简介golang的连接超时和读写超时设置。
1.超时设置
1.1 连接超时
func DialTimeout(network, address string, timeout time.Duration) (Conn, error)
第三个参数timeout
可以用来设置连接超时设置。
如果超过timeout
的指定的时间,连接没有完成,会返回超时错误。
1.2 读写超时
在Conn
定义中,包括读写的超时时间设置。
type Conn interface {
// SetDeadline sets the read and write deadlines associated
// with the connection. It is equivalent to calling both
// SetReadDeadline and SetWriteDeadline.
//
... ...
SetDeadline(t time.Time) error
// SetReadDeadline sets the deadline for future Read calls
// and any currently-blocked Read call.
// A zero value for t means Read will not time out.
SetReadDeadline(t time.Time) error
// SetWriteDeadline sets the deadline for future Write calls
// and any currently-blocked Write call.
// Even if write times out, it may return n > 0, indicating that
// some of the data was successfully written.
// A zero value for t means Write will not time out.
SetWriteDeadline(t time.Time) error
}
通过上面的函数说明,可以得知,这里的参数t
是一个未来的时间点,所以每次读或写之前,都要调用SetXXX
重新设置超时时间,
如果只设置一次,就会出现总是超时的问题。
2.例子
2.1 server
server端监听连接,如果收到连接请求,就是创建一个goroutine负责这个连接的数据收发。
为了测试超时,我们在写操作之前,sleep 3s。
package main
import (
"net"
"log"
"time"
)
func main() {
addr := "0.0.0.0:8080"
tcpAddr, err := net.ResolveTCPAddr("tcp",addr)
if err != nil {
log.Fatalf("net.ResovleTCPAddr fail:%s", addr)
}
listener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
log.Fatalf("listen %s fail: %s", addr, err)
} else {
log.Println("listening", addr)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Println("listener.Accept error:", err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
var buffer []byte = []byte("You are welcome. I'm server.")
for {
time.Sleep(3*time.Second)// sleep 3s
n, err := conn.Write(buffer)
if err != nil {
log.Println("Write error:", err)
break
}
log.Println("send:", n)
}
log.Println("connetion end")
}
2.2 client
client建立连接时,使用的超时时间是3s。
创建连接成功后,设置连接的读超时。
每次读之前,都重新设置超时时间。
package main
import (
"log"
"net"
"os"
"time"
)
func main() {
connTimeout := 3*time.Second
conn, err := net.DialTimeout("tcp", "127.0.0.1:8080", connTimeout) // 3s timeout
if err != nil {
log.Println("dial failed:", err)
os.Exit(1)
}
defer conn.Close()
readTimeout := 2*time.Second
buffer := make([]byte, 512)
for {
err = conn.SetReadDeadline(time.Now().Add(readTimeout)) // timeout
if err != nil {
log.Println("setReadDeadline failed:", err)
}
n, err := conn.Read(buffer)
if err != nil {
log.Println("Read failed:", err)
//break
}
log.Println("count:", n, "msg:", string(buffer))
}
}
输出结果
2019/05/12 16:18:19 Read failed: read tcp 127.0.0.1:51718->127.0.0.1:8080: i/o timeout
2019/05/12 16:18:19 count: 0 msg:
2019/05/12 16:18:20 count: 28 msg: You are welcome. I'm server.
2019/05/12 16:18:22 Read failed: read tcp 127.0.0.1:51718->127.0.0.1:8080: i/o timeout
2019/05/12 16:18:22 count: 0 msg: You are welcome. I'm server.
2019/05/12 16:18:23 count: 28 msg: You are welcome. I'm server.
2019/05/12 16:18:25 Read failed: read tcp 127.0.0.1:51718->127.0.0.1:8080: i/o timeout
2019/05/12 16:18:25 count: 0 msg: You are welcome. I'm server.
2019/05/12 16:18:26 count: 28 msg: You are welcome. I'm server.
golang网络通信超时设置的更多相关文章
- golang RPC通信读写超时设置
golang RPC通信中,有时候就怕读写hang住. 那是否可以设置读写超时呢? 1.方案一: 设置连接的读写超时 1.1 client RPC通信基于底层网络通信,可以通过设置connection ...
- delphi tidhttp 超时设置无效的解决方法
现在delphi都发布到xe8了,tidhttp还有缺陷,那就是超时设置在没有网络或者连不上服务器的时候是无效的,不管你设置为多少都要10-20秒.connectTimeout和readTimeout ...
- Linux串口中的超时设置
在Linux下使用串口通信时,默认的阻塞模式是不实用的.而采用select或epoll机制的非阻塞模式,写代码有比较麻烦.幸好Linux的串口自己就带有超时机制. Linux下使用termios.h中 ...
- org.apache.http.client.HttpClient; HttpClient 4.3超时设置
可用的code import org.apache.commons.lang.StringUtils;import org.apache.http.HttpEntity;import org.apac ...
- HttpClient 3.X 4.3 4.x超时设置
HttpClient 4.3.HttpClient这货和Lucene一样,每个版本的API都变化很大,这有点让人头疼.就好比创建一个HttpClient对象吧,每一个版本的都不一样, 3.X是这样的 ...
- Apache性能优化、超时设置,linux 重启apache
在httpd.conf中去掉Include conf/extra/httpd-default.conf前的#以使httpd-default.php生效.其中调节以下参数Timeout 15 (连接超时 ...
- libcurl多线程超时设置不安全(转)
from http://www.cnblogs.com/kex1n/p/4135263.html (1), 超时(timeout) libcurl 是 一个很不错的库,支持http,ftp等很多的协议 ...
- golang chan 超时
golang chan 超时 Posted on 2013-12-24 13:03 oathleo 阅读(4227) 评论(0) 编辑 收藏 package main import ( &q ...
- CXF超时设置
转自: http://peak.iteye.com/blog/1285211 http://win.sy.blog.163.com/blog/static/9419718620131014385644 ...
随机推荐
- 小米Air 13.3 安装Arch Linux
0. 前言 最近新买了一台小米Air 13.3,除了但键盘手感外都比较满意.我比较喜欢折腾Linux,但又不想放弃原有的Windows 10 Home,于是在原有的windows 10基础上再安装了A ...
- 可靠的TCP连接为何是三次握手和四次挥手
首先,咱们先来熟悉下经典的tcp/ip模型. tcp/ip 模型为了方便使用,将osi七层模型划分成了四层,分别为网络接口层,网络层,传输层,应用层. 他们作用分别为: 1)网络接口层:主要作用是将i ...
- dead relu and Tensorboard
https://medium.com/analytics-vidhya/is-relu-dead-27943b50102 1.使用relu作为激活函数时,因其在输入小于0时,输出为0,所以可能会造成d ...
- windows调试之命令行窗口问题
CProProcess::InitProProcess(_T("safeProcessDemo")); cout << "Enter 'q' to exit: ...
- 关于@wraps(fn)
- 根据IP 自动识别国家和城市
https://www.jianshu.com/p/1b1a018ae729 根据IP 自动识别国家和城市
- Gym - 102082G What Goes Up Must Come Down (树状数组+贪心)
题意:有一个长度为n的序列,你每次可以选择两个相邻的元素交换,求把这个序列排成单峰序列的最少交换次数. 方法一:将元素按数值从大到小排序(保存原来的位置),把最大的插在中间,剩下的依次往两边放,依次考 ...
- 乱花渐入迷人眼------从解决jqueryEasyUI上传插件提交ajax请求谈网页调试
由于要给格斗男神写搏击俱乐部ERP系统,就要用到jquery Easyui插件规范数据和表单的录入,其中一项功能就是上传商品图片, 而且是在datagrid-detailview中使用filebox完 ...
- 【weblogic】WTC配置(Weblogic Tuxedo Connector)
记录下工作中涉及到的WTC使用 WTC 是BEA 的WEB支持产品Weblogic和中间件产品Tuxedo之间的连接工具,全称Weblogic Tuxedo Connector.WTC使Weblogi ...
- i3wm
1.音量调节(alsa-utils) alsamixer: alsamixer is a graphical mixer program for the Advanced Linux Sound Ar ...