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 ...
随机推荐
- xml_SAX解析
(一)SAX解析 1.1 SAX解析 SAX:基于事件处理的机制 sax解析xml文件时,遇到根开始标签,根结束标签,开始解析文件,文件解析结束,字符内容,空白字符等都会触发各自的方法. 优点: 适合 ...
- 13 Zabbix4.4.1系统告警“More than 75% used in the configuration cache”
点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 13 Zabbix4.4.1系统告警“More than 75% used in the conf ...
- 关于Vue-$router传参出现刷新页面或者返回页面丢失数据的问题
也算是踩到坑了,但不是我踩到的,不过还是得说下这个问题,很严重,对于小白和初学者是比较有帮助的,如果使用到路由传参,请选择你想要的传参方式params或者query 1.query this.$rou ...
- ubuntu下usb抓包方法步骤--usbmon
开发或者调试USB设备相关的工具或者驱动,一个调试的利器就是usbmon抓包. 在ubuntu下使用步骤如下: 1 运行命令 sudo mount -t debugfs none /sys/ke ...
- 第二章 Vue快速入门-- 19 v-if和v-show的使用和特点
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...
- Mac破解软件 “XXX”意外退出 奔溃解决方法
最近很多破解软件提示“XXX”意外退出.这是因为苹果在7月12日删除了TNT的证书,所以大部分TNT破解的Mac软件会出现无法打开,提示意外退出. 目前的解决办法是在终端执行命令: 1.首先安装“A ...
- 程序流程图、N-S图、PAD图
在需求分阶段经常使用3种方法去剖析我们所面对的业务. 程序流程图 任何复杂的程序图都应由5种基本控制结构组成或嵌套而成. 盒图(N-S图) Nassi和Scheiderman提出了一种符合结构化程序设 ...
- 三大方面,分析 to B和 to C产品的区别
作为互联网从业者,我们经常听到to B(或2B)和to C(或2C)两个概念.to B即面向企业客户,to C即面向普通用户.只要是互联网人基本都懂知道这两个概念,但如果别人再问“to B和to C产 ...
- window下,nodejs安装http-server,并开启HTTP服务器
1.下载nodejs 官方下载地址:https://nodejs.org/en/ 2.在cmd命令中,输入node -v 输入出版本号,代表安装成功. 3.输入 npm install http-s ...
- vue 项目, 通知子组件更新,父组件中每次点击按钮重新加载子组件,(重新生成dom 元素)
vue是组件化开发的项目,很多情况下会把公共组件提取出来,来减少代码量,提高开发效率,和以后更好的可维护性.很多情况下,父组件中都会引用子组件这种情况.通过给在父组件中引用的子组件标签上添加属性,来渲 ...