dousao1175 2017-12-20 18:28
浏览 599
已采纳

TCP服务器中的IdleTimeout

I am working on a project in the Go language which includes TCP server. I am trying to implement an idle timeout on server sockets, but couldn't do it. The Go code I am using goes like this:

package main

import (
    "bufio"
    "fmt"
    "net"
    "os"
    "strconv"
    "time"
)

func main() {
    startServer(6666, time.Duration(2)*time.Second)
}

func startServer(port int, deadline time.Duration) {
    // Listen for incoming connections.
    strPort := strconv.Itoa(port)
    l, err := net.Listen("tcp", ":"+strPort)
    if err != nil {
        fmt.Println("Error listening:", err.Error())
        os.Exit(1)
    }
    // Close the listener when the application closes.
    defer l.Close()
    fmt.Println("Listening on port:" + strPort)
    for {
        // Listen for an incoming connection.
        conn, err := l.Accept()
        if err != nil {
            fmt.Println("Error accepting: ", err.Error())
            os.Exit(1)
        }

        fmt.Println("Got new connection")

        // Set read timeout
        conn.SetReadDeadline(time.Now().Add(deadline))

        // Handle connections in a new goroutine.
        go handleRequest(conn)
    }
}

func handleRequest(conn net.Conn) {
    reader := bufio.NewReader(conn)
    scanner := bufio.NewScanner(reader)

    for scanner.Scan() {
        fmt.Println(scanner.Bytes())
    }
}

I want it to timeout and close the connection after 2 seconds. Could anybody please tell me what I might be doing wrong. In order to test it, I am using a TCP client I wrote as Python scipt. The client code goes like this:

λ python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from socket import *
>>> c = socket(family=AF_INET, type=SOCK_STREAM)
>>> c.connect(('localhost', 6666))

I can always keep track of all the open connections, along with their last active time in some sort of data structure and launch a goroutine which periodically checks for time elapsed for every connection, closing the ones I haven't heard from in a while. But I wanted to utilize the built-in method SetReadDeadline() for the job.

  • 写回答

1条回答 默认 最新

  • duanbi8089 2017-12-20 18:55
    关注

    In the net package documentation for SetDeadline, it states

       // An idle timeout can be implemented by repeatedly extending
       // the deadline after successful Read or Write calls.
    

    You do this by creating your own net.Conn type to implement the call you want to have timeout. Since an idle connection would normally be waiting in Read, that is usually where you want to set the deadline.

    type Conn struct {
        net.Conn
        idleTimeout time.Duration
    }
    
    func (c *Conn) Read(b []byte) (int, error) {
        err := c.Conn.SetReadDeadline(time.Now().Add(c.idleTimeout))
        if err != nil {
            return 0, err
        }
        return c.Conn.Read(b)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?