Skip to content

Instantly share code, notes, and snippets.

@feix
Forked from hongster/tcp_timeout.go
Created June 12, 2018 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feix/5f3ac7a549fb10744991f4355f73b4ab to your computer and use it in GitHub Desktop.
Save feix/5f3ac7a549fb10744991f4355f73b4ab to your computer and use it in GitHub Desktop.
Golang example on handling TCP connection and setting timeout.
package main
import (
"fmt"
"net"
"time"
"bufio"
)
func handleConnection(conn net.Conn) {
fmt.Println("Handling new connection...")
// Close connection when this function ends
defer func() {
fmt.Println("Closing connection...")
conn.Close()
}()
timeoutDuration := 5 * time.Second
bufReader := bufio.NewReader(conn)
for {
// Set a deadline for reading. Read operation will fail if no data
// is received after deadline.
conn.SetReadDeadline(time.Now().Add(timeoutDuration))
// Read tokens delimited by newline
bytes, err := bufReader.ReadBytes('\n')
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%s", bytes)
}
}
func main() {
// Start listening to port 8888 for TCP connection
listener, err:= net.Listen("tcp", ":8888")
if err != nil {
fmt.Println(err)
return
}
defer func() {
listener.Close()
fmt.Println("Listener closed")
}()
for {
// Get net.TCPConn object
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
break
}
go handleConnection(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment