2

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.

JimB
  • 104,193
  • 13
  • 262
  • 255
Prakhar Mishra
  • 1,586
  • 4
  • 28
  • 52
  • I don't see what you're doing for an idle timeout here at all. The docs state: `An idle timeout can be implemented by repeatedly extending the deadline after successful Read or Write calls.`. Have you tried that? – JimB Dec 20 '17 at 18:31
  • I want it to timeout in the first place. Extending comes after this. The point is, its not closing my connection. **netstat -a** still shows active connections, even after 2 secs of connection. – Prakhar Mishra Dec 20 '17 at 18:34
  • Yes, so every Read (and/or Write) you set a new deadline. – JimB Dec 20 '17 at 18:38
  • But, I want to end `idle` connections. Using my python client, I want to simulate an idle connection (by sending nothing to the server). Now, Ideally, it should close the connection after 2 seconds, but it isn't. – Prakhar Mishra Dec 20 '17 at 18:42
  • Timeouts don't close connections. That's always up to you to properly call Close. – JimB Dec 20 '17 at 18:45
  • Is there some sort of callback I need to pass to close an idle connection? How can I handle idle timeout events? – Prakhar Mishra Dec 20 '17 at 18:50
  • The "callbacks" are the Read and Write calls themselves. I'll add an example of an idle timeout, but calling Close is always required. `c.settimeout(1)` and `c.recv(1)` in python isn't going to close the connection either. – JimB Dec 20 '17 at 18:52

1 Answers1

7

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)
}
JimB
  • 104,193
  • 13
  • 262
  • 255
  • Thanks for the answer. But where are we closing connection? – Prakhar Mishra Dec 20 '17 at 19:00
  • That's up to your code. You close the connection when you're done with it. If the timeout was reached, the Read will return, and you'll have a deadline error. – JimB Dec 20 '17 at 19:01
  • Ok. Have you any idea of how can I make it work with `bufio.Scanner`? The code is written that way (using scanner). Can I make `scanner.Scan` call return after either read bytes or N seconds? – Prakhar Mishra Dec 20 '17 at 19:24
  • That's what this does already. The fact that you're using `bufio.Scanner` is beside the point. – JimB Dec 20 '17 at 19:31