网络通信中,为了防止长时间无响应的情况,经常会用到网络连接超时、读写超时的设置。

本文结合例子简介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网络通信超时设置的更多相关文章

  1. golang RPC通信读写超时设置

    golang RPC通信中,有时候就怕读写hang住. 那是否可以设置读写超时呢? 1.方案一: 设置连接的读写超时 1.1 client RPC通信基于底层网络通信,可以通过设置connection ...

  2. delphi tidhttp 超时设置无效的解决方法

    现在delphi都发布到xe8了,tidhttp还有缺陷,那就是超时设置在没有网络或者连不上服务器的时候是无效的,不管你设置为多少都要10-20秒.connectTimeout和readTimeout ...

  3. Linux串口中的超时设置

    在Linux下使用串口通信时,默认的阻塞模式是不实用的.而采用select或epoll机制的非阻塞模式,写代码有比较麻烦.幸好Linux的串口自己就带有超时机制. Linux下使用termios.h中 ...

  4. org.apache.http.client.HttpClient; HttpClient 4.3超时设置

    可用的code import org.apache.commons.lang.StringUtils;import org.apache.http.HttpEntity;import org.apac ...

  5. HttpClient 3.X 4.3 4.x超时设置

    HttpClient 4.3.HttpClient这货和Lucene一样,每个版本的API都变化很大,这有点让人头疼.就好比创建一个HttpClient对象吧,每一个版本的都不一样, 3.X是这样的 ...

  6. Apache性能优化、超时设置,linux 重启apache

    在httpd.conf中去掉Include conf/extra/httpd-default.conf前的#以使httpd-default.php生效.其中调节以下参数Timeout 15 (连接超时 ...

  7. libcurl多线程超时设置不安全(转)

    from http://www.cnblogs.com/kex1n/p/4135263.html (1), 超时(timeout) libcurl 是 一个很不错的库,支持http,ftp等很多的协议 ...

  8. golang chan 超时

    golang chan 超时 Posted on 2013-12-24 13:03 oathleo 阅读(4227) 评论(0)  编辑  收藏 package main import (    &q ...

  9. CXF超时设置

    转自: http://peak.iteye.com/blog/1285211 http://win.sy.blog.163.com/blog/static/9419718620131014385644 ...

随机推荐

  1. Nginx配置,请求到tomcat中

    一.web服务器分为两类 1.web服务器 1)Apache服务器 2)Nginx 3)IIS 2.web 应用服务器 1)tomcat 2)resin 3)jetty 区分:web服务器不能解析js ...

  2. 检查linux是否安装java、tomcat、mysql

    linux下,查看安装软件 1.linux下的java Java -version 如果出现java版本,证明java安装成功. 2.linux下的tomcat 2.1.检查linux是否安装tomc ...

  3. 从FBV到CBV二(认证器)

    span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }.CodeMirror ...

  4. 在centos7上kvm网卡桥接

    系统环境准备 [root@linux-node1 ~]# cat /etc/redhat-release CentOS Linux release (Core) [root@linux-node1 ~ ...

  5. 利用nethogs查看哪些进程占用网络带宽

    一.安装nethogs centos6版本安装: 1.安装依赖包 [root@hlsms-fensheng- ~]# yum install ncurses* 已加载插件:fastestmirror, ...

  6. java String练习

    package com.oracle.demo01; public class WorkNext { public static void main(String[] args) { //题目一:获取 ...

  7. 完整的IT项目开发流程

    一般情况下,企业开发软件时会按照基线和定制两块并行方式执行项目开发工作.无论什么公司,都需要遵从一套成熟的产品研发过程体系,才能做出质量较好的产品.因此,如果出现项目较多的情况,应该合理地安排基线和定 ...

  8. python广度遍历文件夹

    import os from collections import deque path = r"E:\Python" queue = deque([])#队列 queue.app ...

  9. hiho #1032: 最长回文子串

    #1032 : 最长回文子串 时间限制:1000ms 单点时限:1000ms 内存限制:64MB 描述 小Hi和小Ho是一对好朋友,出生在信息化社会的他们对编程产生了莫大的兴趣,他们约定好互相帮助,在 ...

  10. django admin登陆页出现TypeError at /admin/

    出现此错误的原因主要是,添加多条URL时urlpatterns后面的序列符号写错了,检查所有的urls.py文件将{}改为[]. error: urlpatterns = {} right: urlp ...