Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.